为 ggplot() 添加水平线,指定 x 轴的间隔

问题描述 投票:0回答:3

我想向现有绘图添加水平线,但我只想在 x 轴的某些间隔内绘制该线。

例如,我想在 X=1:5 和 y=50 处有一条水平线。

我会用

existing_plot+geom_hline(yintercept = 50)

是否也可以以某种方式指定 x 值?

r ggplot2
3个回答
38
投票

您可以使用

geom_segment()
添加具有您自己定义的起点和终点的线段(不仅是水平/垂直线)。

ggplot(mtcars,aes(mpg,qsec))+geom_point()+
  geom_segment(aes(x=15,xend=20,y=18,yend=18))

enter image description here


8
投票

您可以使用

geom_line

qplot(x=x,y=y,data=data.frame(x=1:10,y=100:1)) +
  geom_line(data=data.frame(x=1:5,y=50))

enter image description here


0
投票

还有

annotate
选项。

@Didzis 的解决方案当然有效,但是当我使用它时,我收到了警告:

library(ggplot2)

ggplot(mtcars, aes(x = wt, y = hp)) +
    geom_point() +
    geom_segment(aes(x = 2, xend = 4, y = 250, yend = 250),
                 colour = "red", linewidth = 1)

“警告信息: 在geom_segment(aes(x = 2,xend = 4,y = 250,yend = 250)中,颜色=“红色”,: 所有的美学长度都是1,但是数据有32行。 ℹ 请考虑使用

annotate()
或为该层提供包含单行的数据。”

他们的文档中甚至有这些警告与位置相关的美学:x,y,xmin,xmax,ymin,ymax,xend,yend

根据警告的建议,我们有:

ggplot(mtcars, aes(x = wt, y = hp)) +
    geom_point() +
    annotate("segment", x = 2, xend = 4, y = 250, yend = 250,
             col = "red", linewidth = 1)

产生完全相同的情节并产生NO警告。

我在文档中找不到任何有关此警告或首选方法的内容(例如

?geom_segment
和建议的小插图
vignette("ggplot2-specs")
)。

© www.soinside.com 2019 - 2024. All rights reserved.