从ggplot2中的特定geom_point()画一条对角线

时间:2019-03-17 12:21:54

标签: r ggplot2 dplyr

我想从ggplot2中的特定geom_point()开始画一条对角线。该线将从点(x = 21y = 0.37)开始,并在第一个点和最后一个点之间产生的对角线处结束(请参见下文:)

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

df <- structure(list(x = c(0, 8, 12, 16, 20, 24, 28, 32, 33.33), y = c(0.2, 
                                                                       0.212, 0.22, 0.26, 0.339, 0.452, 0.654, 1.001, 1.155)), class = c("tbl_df", 
                                                                                                                                         "tbl", "data.frame"), row.names = c(NA, -9L))

df %>% 
  ggplot(aes(x, y)) +
  geom_point(shape = 21, size = 4) +
  geom_smooth(data = filter(df, row_number() %in% c(1, n())), method = "lm") +
  geom_point(aes(x = 21, y = .37), shape = 21, size = 4, fill = "blue") +
  theme_light()
#> Warning in qt((1 - level)/2, df): NaNs produced

reprex package(v0.2.1)于2019-03-17创建

编辑:

我想要的结果示例:

enter image description here

1 个答案:

答案 0 :(得分:2)

由于我稍后将要解释的原因,这不是一个好看的解决方案。但这确实符合问题的要求。

首先,辅助功能。

#
# computes the intersection point of the 
# line passing through x perpendicular to
# the line defined by PQ
#
perp_line <- function(x, P, Q){
  a <- Q[2] - P[2]
  b <- -(Q[1] - P[1])
  A <- matrix(c(a, b, b, -a), nrow = 2)
  c1 <- -b*P[2] - a*P[1]
  c2 <- -b*x[1] + a*x[2]
  cc <- c(-c1, -c2)
  solve(A, cc)
}

现在使用该函数获取所需点的坐标,并从蓝点到计算出的点绘制一条线段。

X <- unlist(df[1, ])
Y <- unlist(df[nrow(df), ])
Z <- perp_line(c(21, 0.37), X, Y)

df %>% 
  ggplot(aes(x, y)) +
  geom_point(shape = 21, size = 4) +
  geom_smooth(data = filter(df, row_number() %in% c(1, n())), method = "lm") +
  geom_point(aes(x = 21, y = .37), shape = 21, size = 4, fill = "blue") +
  geom_segment(aes(x = x2, y = y2, xend = Z[1], yend = Z[2])) +
  #coord_fixed(ratio = 1) +
  theme_light()

从图中可以看出,纵横比非常糟糕。您的xy轴范围是如此不同,以至于线条看起来不是垂直的。取消注释coord_fixed代码行以获取更好的宽高比,但是您将看不到任何内容。

enter image description here