如何为图中的每个条添加单独的 hlines?

时间:2021-06-07 14:24:54

标签: r ggplot2

给定一个数据框和一个图如下:

library(dplyr)
library(ggplot2)

dat <- data.frame(grp = c("a", "b", "c"),
           val = c(30, 20, 10),
           avg = c(25, 15, 5)) 

dat %>% 
  ggplot(aes(x = grp, y = val)) +
  geom_bar(stat = "identity")

如何修改上面的代码以在每个条形上放置唯一的水平参考线 (avg),如下所示:

enter image description here

1 个答案:

答案 0 :(得分:3)

这可以通过像这样的 geom_segment 来实现,我首先将 grp 转换为数字并对应于 0.9 条的默认宽度将 x 设为 0.45向左,xend 在 0.45 处向右:

library(ggplot2)

dat <- data.frame(grp = c("a", "b", "c"),
                  val = c(30, 20, 10),
                  avg = c(25, 15, 5)) 

ggplot(dat, aes(x = grp, y = val)) +
  geom_bar(stat = "identity") +
  geom_segment(aes(y = avg, yend = avg, 
                   x = as.numeric(factor(grp)) - .45, 
                   xend = as.numeric(factor(grp)) + .45), color = "red")

编辑 感谢@tjebo 的评论:由于硬编码很少是一个好主意,因此可以通过变量设置宽度:

w <- .9
...
geom_segment(aes(y = avg, yend = avg, 
                       x = as.numeric(factor(grp)) - w/2, 
                       xend = as.numeric(factor(grp)) + w/2), color = "red")

enter image description here

相关问题