r - 如何在 ggplot2 中使用 geom_ribbon 为 geom_hline 制作错误栏?

标签 r errorbar geom-hline

我希望我的 geom_hline 有一个误差栏,并认为具有不透明度的 geom_ribbon 看起来最好。但我不知道如何让它到达情节的终点。我希望 geom_ribbon 像 geom_hline 那样接触绘图的侧面。下面是示例代码:

library('ggplot2')

x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(1,2,3,4,5,6,7,8,9,10)

data <- data.frame(x,y)

p1 <- ggplot(data,aes(x = x, y = y)) + geom_line() + geom_hline(yintercept=5)

p1 + geom_ribbon(aes(y = y[5],ymin = y[5]-0.5, ymax = y[5]+0.5, fill = 'red'), alpha = 0.4) 

enter image description here

最佳答案

使用具有无限 x 值的注释:

ggplot(data, aes(x, y)) + 
  geom_line() + 
  geom_hline(yintercept = 5) +
  annotate('ribbon', x = c(-Inf, Inf), ymin = 5 - 0.5, ymax = 5 + 0.5, 
           alpha = 0.4, fill = 'red')

enter image description here

如果您需要图例,请直接使用geom_ribbon,如下所示:

ggplot(data, aes(x, y)) + 
  geom_line() + 
  geom_hline(yintercept = 5) +
  geom_ribbon(
    aes(x, y = NULL, ymin = ymin, ymax = ymax, fill = 'my_label'), 
    data.frame(x = c(-Inf, Inf), ymin = 5 - 0.5, ymax = 5 + 0.5),
    alpha = 0.4
  )

关于r - 如何在 ggplot2 中使用 geom_ribbon 为 geom_hline 制作错误栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941534/

相关文章:

r - 使用 ggplot 和 facet_grid 指定误差线

r - 如何在R中的不同方面产生不同的geom_vline?

r - ggplot : Add different lines in each facet of geom_bar

r - Gurobi 软件包未在 Ubuntu 14.04 中加载,dyn.load(文件,DLLpath = DLLpath,...): 中出错

r - 标签与背景对比 : determine if color is light or dark

r - ggplot2 - 用点躲避水平误差线

从 ggplot2 中的误差条中删除端点

r - 如何在同一个散点图上使用 geom_vline() 和 geom_hline 避免图例中的交叉效应?

r - 创建新的强调命令 R Markdown

r - R data.table 中的分组计数聚合