ggbarplot中最后一条柱形的mean_se误差线与柱顶不对齐问题求助
问题说明
我用ggpubr绘制柱状图,用来比较Condition变量,同时按Geno分面。图表整体效果没问题,但最右侧的柱形存在异常:它的mean_se误差线落在了柱形阴影区域的中间。
绘图代码
plot = ggbarplot(filtered_df, x = "Condition", y = "ScrapeNitrite", fill = "Condition", add = c("mean_se", "jitter"), facet.by="Geno", palette = c("white", "grey", "darkgrey","black")) + scale_y_continuous(limits = c(0,100), expand = c(0, 0)) + theme_prism()
数据集
# A tibble: 16 × 3 Condition ScrapeNitrite Geno <fct> <dbl> <fct> 1 naïve 16.9 FF 2 naïve 9.28 FF 3 DSS 15.2 dIEC 4 DSS 23.6 FF 5 DSS 48.8 FF 6 DSS 37.7 FF 7 DSS 34.7 FF 8 DSS 35.7 FF 9 naïve 5.09 dIEC 10 DSS 35.8 dIEC 11 DSS 6.33 dIEC 12 DSS 151. dIEC 13 DSS 13.5 dIEC 14 DSS -2.84 dIEC 15 DSS 20.8 dIEC 16 naïve 28.2 FF
问题原因与解决办法
原因
你设置了scale_y_continuous(limits = c(0,100)),但dIEC组的DSS条件里有个151的异常值,还有-2.84的负值。ggpubr计算mean_se时基于原始全量数据,均值和标准差被151拉高,但柱形因y轴限制被截断到100,导致误差线看起来落在柱形中间。
解决办法
有三种可行思路:
- 截断数据后绘图:过滤掉超出y轴范围的数据,让统计计算和可视化基于同一数据集:
# 过滤0-100之间的数据 filtered_df_truncated = filtered_df %>% filter(ScrapeNitrite >= 0, ScrapeNitrite <= 100) # 用过滤后的数据重新绘图 plot = ggbarplot(filtered_df_truncated, x = "Condition", y = "ScrapeNitrite", fill = "Condition", add = c("mean_se", "jitter"), facet.by="Geno", palette = c("white", "grey", "darkgrey","black")) + scale_y_continuous(limits = c(0,100), expand = c(0, 0)) + theme_prism()
- 用坐标截断替代轴限制:改用
coord_cartesian设置显示范围,统计计算仍用原始数据,误差线会对应真实均值:
plot = ggbarplot(filtered_df, x = "Condition", y = "ScrapeNitrite", fill = "Condition", add = c("mean_se", "jitter"), facet.by="Geno", palette = c("white", "grey", "darkgrey","black")) + coord_cartesian(ylim = c(0,100), expand = FALSE) + theme_prism()
- 修正/移除异常值:如果151是录入错误,直接修正或删除该数据点,统计结果会更贴合实际分布。
内容的提问来源于stack exchange,提问作者Bryce Hunt
相关产品推荐
相关产品推荐

