柱状图误差线位置异常求助:误差线未以均值为中心分布
ggplot2柱状图误差线位置异常的解决办法
问题描述
使用R语言ggplot2绘制柱状图时,发现部分误差线位于柱子正下方,未围绕均值呈±分布。
用户提供的代码与数据
绘图脚本
psbs <- read_csv("psbs.csv") spsbs<-summarySE(data=psbs, measurevar="fv", groupvars=c("Line", "genotype")) P1<- ggplot(data=psbs, mapping = aes(x = factor(genotype), y = fv, fill= Line))+ geom_bar(stat = "identity", position = "dodge")+ geom_errorbar(data=spsbs, aes(ymin=fv-se, ymax=fv+se), width=.35, position=position_dodge(width= 0.9))+ theme_bw()+ theme(text = element_text(size = 13))+ theme(axis.text.x=element_blank())+ facet_wrap(~genotype,scales="free")+ ylim(0,1.0)+ labs(x = element_blank(), y="Fv/Fm", fill= "Line")
原始数据框
data.frame(psbs) id genotype Line fv 1 1 PsbS L1.1 0.82 2 2 PsbS L1.1 0.82 3 3 PsbS L1.1 0.82 4 4 PsbS L1.2 0.82 5 5 PsbS L1.2 0.82 6 6 PsbS L1.2 0.82 7 7 PsbS L1.3 0.82 8 8 PsbS L1.3 0.82 9 9 PsbS L1.3 0.83 10 10 PsbS L1.4 0.82 11 11 PsbS L1.4 0.82 12 12 PsbS L1.4 0.82 13 13 PsbS L1.5 0.82 14 14 PsbS L1.5 0.83 15 15 PsbS L1.5 0.82 16 16 PsbS L1.6 0.82 17 17 PsbS L1.6 0.82 18 18 PsbS L1.6 0.83 19 19 PsbS L1.7 0.82 20 20 PsbS L1.7 0.82 21 21 PsbS L1.7 0.82 22 22 PsbS L1.8 0.83 23 23 PsbS L1.8 0.82 24 24 PsbS L1.8 0.82 25 25 PsbS L1.9 0.82 26 26 PsbS L1.9 0.83 27 27 PsbS L1.9 0.82
问题原因
当前柱状图使用原始数据psbs绘制,geom_bar(stat="identity")会将每个观测值单独绘制成柱子(每个Line下的3个重复值对应3个重叠的柱子),而误差线基于汇总后spsbs的均值±标准误,两者高度基准不匹配,导致误差线与柱子位置错位。
修正后的代码
psbs <- read_csv("psbs.csv") spsbs <- summarySE(data=psbs, measurevar="fv", groupvars=c("Line", "genotype")) P1 <- ggplot(data=spsbs, mapping = aes(x = factor(Line), y = fv, fill= Line)) + geom_bar(stat = "identity", position = "dodge") + geom_errorbar(aes(ymin=fv-se, ymax=fv+se), width=.35, position=position_dodge(width= 0.9)) + theme_bw() + theme(text = element_text(size = 13)) + facet_wrap(~genotype, scales="free") + coord_cartesian(ylim=c(0,1.0)) + # 替代ylim,避免截断数据 labs(x = "Line", y="Fv/Fm", fill= "Line")
优化说明
- 改用汇总后的
spsbs绘制柱状图,确保柱子高度与误差线均基于分组均值,位置匹配。 - 将x轴改为
Line,结合genotype分面,每个面板内展示对应基因型下的不同品系,图表逻辑更清晰。 - 用
coord_cartesian(ylim=c(0,1.0))替换ylim(0,1.0),仅缩放坐标轴,不会过滤超出范围的误差线数据。 - 移除
axis.text.x=element_blank(),显示x轴品系标签,提升可读性。
内容的提问来源于stack exchange,提问作者wychin
相关产品推荐
相关产品推荐

