【问题标题】:Add dynamic 45 degree line to ggplot scatterplot将动态 45 度线添加到 ggplot 散点图
【发布时间】:2021-08-20 09:51:57
【问题描述】:

我想为 ggplot 图创建一条附加线,该线会根据显示值的比例进行动态调整。我想添加这一行,以便快速查看其中一个类别是否始终大于另一个类别。 因此,如果我可以将线添加到独立于关卡的每个情节中,那就太好了。

  library(dplyr)
  library(ggplot2)
  test <- structure(list(Date = c("202107", "202106", "202104", "202102", 
            "202101", "202105", "202103"), Val1 = c(199165942214.504, 200405660266.164, 
             194931793612.389, 187140775347.389, 186193256330.389, 196323803492.389, 
             191885428112.389), Val2 = c(194546158558, 195351933631, 188748709692, 
             181522458543, 180653727026, 190427709692, 186599848808)), row.names = c(NA, 
             -7L), class = c("tbl_df", "tbl", "data.frame")
      
  test %>%
  ggplot(., aes(x=Val1, y = Val2)) + 
  geom_point()
  
  # Not working, because of the wrong intercept.
  test %>%
  ggplot(., aes(x=Val1, y = Val2)) + 
  geom_point() +
  geom_abline(intercept = 0, slope = 1, size = 0.5)

此答案中提出的解决方案显然不起作用https://stackoverflow.com/a/67182543/5795592

【问题讨论】:

    标签: r ggplot2 dplyr tidyverse


    【解决方案1】:

    我不明白问题是什么。它在数据空间中绘制了一条 45 度线。如果希望它在图形空间中为 45 度,则需要设置坐标,使 x 轴上的 1 个单位与 y 轴上的 1 个单位等长。

    这似乎是正确的:

    library(dplyr)
    library(ggplot2)
    test <- structure(list(
      Date = c("202107", "202106", "202104", "202102", 
               "202101", "202105", "202103"), 
      Val1 = c(199165942214.504, 200405660266.164, 
               194931793612.389, 187140775347.389, 186193256330.389, 196323803492.389, 
               191885428112.389), 
      Val2 = c(194546158558, 195351933631, 188748709692, 
               181522458543, 180653727026, 190427709692, 186599848808)
      ), row.names = c(NA, -7L), class = c("tbl_df", "tbl", "data.frame"))
      
    p <- test %>%
      ggplot(., aes(x=Val1, y = Val2)) + 
      geom_point() +
      geom_abline(intercept = 0, slope = 1, size = 0.5)
    p
    

    我们可以通过扩展限制以包括原点来证明截距是正确的:

    p + xlim(c(0, NA)) + ylim(c(0, NA))
    

    要使数据空间与图形空间相对应,可以设置相等的坐标。

    p + coord_equal()
    

    最后,你可以协调 x 比例和 y 比例限制显示相同的范围:

    p + xlim(range(test$Val1, test$Val2)) + ylim(range(test$Val1, test$Val2)) +
      coord_equal()
    

    reprex package (v1.0.0) 于 2021-08-20 创建

    【讨论】:

    • 抱歉不够清楚。当然,截距为 0 的线是正确的,但我对您在图形空间中定义为 45 度的内容感兴趣。
    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2014-11-20
    • 2021-12-08
    • 2018-08-30
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    相关资源
    最近更新 更多