R ggplot2: Add means as horizontal line in a boxplot

烂漫一生 提交于 2019-12-10 03:26:49

问题


I have created a boxplot using 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()

The boxplot shows the median as a horizontal line across each box.

How do I add a dashed line to the box representing the mean of that group?

Thanks!


回答1:


You can add horizontal lines to plots by using stat_summary with geom_errorbar. The line is horizontal because the y minimum and maximum are set to be the same as 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")



来源:https://stackoverflow.com/questions/40135240/r-ggplot2-add-means-as-horizontal-line-in-a-boxplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!