如何在ggplot2绘制的分组箱线图中显示各分组的均值?
问题解决方法
出现该问题的核心原因是stat_summary默认没有匹配箱线图的分组闪避位置,导致两个分组的均值点都重叠在x轴分类的中心位置,看起来只显示了一个公共均值。
你只需要修改三处代码即可:
- 给
stat_summary添加position = position_dodge(width = 0.75)参数,和箱线图默认的闪避宽度对齐,让均值点分别落在对应分组的箱线图中心 - 替换已被新版本ggplot2弃用的
fun.y参数为fun - 修正原代码中
coord_cartesian()语句后缺失的+号,避免语法报错
修正后的完整代码如下:
ggplot(data = df.08.long, aes(x = TMT_signals, y = as.numeric(TMT_Intensities), fill = `probe.Mod.or.not(Y/N)`)) + geom_boxplot() + stat_summary(fun = mean, geom = "point", shape = 20, size = 5, color = "red", fill = "red", position = position_dodge(width = 0.75)) + coord_cartesian( xlim = NULL, ylim = c(0, 2e4), expand = TRUE, default = FALSE, clip = "on") + theme_classic() + theme(axis.title=element_text(size=8), axis.text=element_text(size=10), axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
如果需要不同分组的均值点也区分颜色,可以把color参数放到aes()里映射probe.Mod.or.not(Y/N)字段即可。
内容的提问来源于stack exchange,提问作者Chemist learns to code
相关产品推荐
相关产品推荐

