R:将“vline”和“hline”语句组合在一起(ggplot2)

sta*_*oob 2 plot r data-visualization scatter-plot ggplot2

我正在使用 R 编程语言。最近,我学习了如何使用 ggplot 库“绘制”水平线和垂直线:

library(ggplot2)

# Simple scatter plot
sp <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()

# Add horizontal line at y = 2O

a = sp + geom_hline(yintercept=20) 

b = sp + geom_vline(xintercept = 3)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在,我尝试将这些陈述结合在一起 - 例如:

c = sp + geom_hline(yintercept=20) +  geom_hline(yintercept=15) + geom_vline(xintercept = 3) +
    geom_vline(xintercept = 5) + geom_vline(xintercept = 6) + geom_hline(yintercept=35)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

问题:我正在尝试修改上面的图,使其看起来像这样:

在此输入图像描述

有人可以告诉我该怎么做吗?或者您是否必须手动将此图导出到 Microsoft Paint 中并在那里进行更改?

谢谢

Jon*_*ing 5

您可以使用添加图层annotate。每个段都是下面四个向量的匹配元素。即第一段从 (-Inf,15) 开始,到 (3,15) 结束。

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
  annotate("segment", 
           x = c(-Inf, 3, -Inf, 5, -Inf, 6),
           y = c(15, 15, 20, 20, 35, 35),
           xend = c(3, 3, 5, 5, 6, 6),
           yend = c(15, -Inf, 20, -Inf, 35, -Inf))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

或者也许定义一个从一点向轴绘制两条线的函数会更容易(假设这里的点是正的,所以它应该朝向 -Inf)。要使函数输出多个 ggplot2 元素,请将它们放入列表中:

draw_guides<- function(x, y) {
  list(geom_segment(aes(x = -Inf, xend = x, y = y, yend = y)),
       geom_segment(aes(x = x, xend = x, y = y, yend = -Inf)))
}
Run Code Online (Sandbox Code Playgroud)

然后您可以调用每一个来更轻松地重新创建所需的图形:

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
  draw_guides(3,15) +
  draw_guides(5,20) +
  draw_guides(6,35)
  
Run Code Online (Sandbox Code Playgroud)