R ggplot2:在箱线图中添加表示为水平线

R ggplot2: Add means as horizontal line in a boxplot

我使用 ggplot2 创建了一个箱线图:

library(ggplot2)

dat <- data.frame(study = c(rep('a',50),rep('b',50)), 
                  FPKM = c(rnorm(1:50),rnorm(1:50)))

ggplot(dat, aes(x = study, y = FPKM)) + geom_boxplot()

箱线图将中位数显示为横跨每个方框的水平线。

如何在表示该组平均值的框中添加虚线?

谢谢!

您可以使用 stat_summarygeom_errorbar 向绘图添加水平线。该线是水平的,因为 y 最小值和最大值设置为与 y 相同。

ggplot(dat, aes(x = study, y = FPKM)) + 
    geom_boxplot() +
    stat_summary(fun.y = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
                 width = .75, linetype = "dashed")