在R语言中如何为堆叠柱状图的每个柱添加误差棒?
解决堆叠柱状图添加整柱误差棒的问题
要给每个堆叠柱状图的整根柱子添加误差棒,你需要先汇总每个location对应的总y值和总误差,再把误差棒定位到整柱的顶部位置。
步骤1:预处理数据
先计算每个location的总y值,以及对应的总误差(这里假设误差为标准误,总标准误通过各部分方差求和后开平方得到:sqrt(sum(se^2)),可根据你的误差类型调整计算逻辑):
library(dplyr) library(ggplot2) # 原始数据 location=c("L1","L2","L1","L2") y=c(5,10,12,12) cat=c("A","A","B","B") se=c(1,2,2,3) df=data.frame(location,y,cat,se) # 汇总每个location的总y和总误差 df_summary <- df %>% group_by(location) %>% summarise( total_y = sum(y), total_se = sqrt(sum(se^2)) )
步骤2:绘制图形
先绘制堆叠柱状图,再用汇总后的数据添加误差棒,将误差棒的y轴定位到整柱的总高度位置:
ggplot(data=df, aes(x=location , y=y, fill=cat))+ geom_bar(stat="identity", position = position_stack(reverse=T), width=0.7, size=1) + # 添加整柱误差棒,使用汇总数据,关闭继承原始映射避免冲突 geom_errorbar(data=df_summary, aes(x=location, y=total_y, ymin=total_y - total_se, ymax=total_y + total_se), width=0.5, inherit.aes = FALSE)
内容的提问来源于stack exchange,提问作者J.K Kim
相关产品推荐
相关产品推荐

