本文小编为大家详细介绍“ggplot2怎么为分组柱状图添加误差线”,内容详细,步骤清晰,细节处理妥当,希望这篇“ggplot2怎么为分组柱状图添加误差线”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
如何针对分组柱状图添加误差线并合理调整位置呢?主要基于geom_errorbar及其参数position进行细节调整。
1、案例数据:
> dat type Sample Num SD 1 A sample1 90 1.0 2 B sample1 34 2.0 3 C sample1 56 1.2 4 D sample1 99 2.0 5 E sample1 15 2.4 6 A sample2 50 1.0 7 B sample2 20 1.0 8 C sample2 24 1.0 9 D sample2 70 1.8 10 E sample2 14 1.5
2、于柱状图上添加geom_errorbar(不控制位置)
针对geom_errorbar设置如下:width是误差线上下端宽度,size是粗细
geom_errorbar(aes(ymin=(Num-SD),ymax=(Num+SD)),width=0.2,size=0.02)
全部绘图代码如下:
p = ggplot(dat, aes(x = type,y = Num,fill = Sample))+ geom_bar(stat ="identity",width = 0.6,position = "dodge")+ geom_errorbar(aes(ymin=(Num-SD),ymax=(Num+SD)),width=0.2,size=0.02)+ scale_fill_manual(values = c("red","blue"))+ labs(x = "",y = "", title = "test")+ geom_text(aes(label = dat$Num),position=position_dodge(width = 0.5),size = 5,vjust = -0.25)+ guides(fill = guide_legend(reverse = F))+ theme(plot.title = element_text(size = 25,face = "bold", vjust = 0.5, hjust = 0.5), legend.title = element_blank(), legend.text = element_text(size = 18, face = "bold"), legend.position = 'right', legend.key.size=unit(0.8,'cm')) print(p)
3、控制位置position="dodge" 与柱状图位置参数一致
绘图代码如下:
p = ggplot(dat, aes(x = type,y = Num,fill = Sample))+ geom_bar(stat ="identity",width = 0.6,position = "dodge")+ geom_errorbar(aes(ymin=(Num-SD),ymax=(Num+SD)),width=0.2,size=0.02,position = "dodge")+ scale_fill_manual(values = c("red","blue"))+ labs(x = "",y = "", title = "test")+ geom_text(aes(label = dat$Num),position=position_dodge(width = 0.5),size = 5,vjust = -0.25)+ guides(fill = guide_legend(reverse = F))+ theme(plot.title = element_text(size = 25,face = "bold", vjust = 0.5, hjust = 0.5), legend.title = element_blank(), legend.text = element_text(size = 18, face = "bold"), legend.position = 'right', legend.key.size=unit(0.8,'cm')) print(p)
4、控制position=position_dodge(width=0.6), 误差线整体间隔和组内柱子整体宽度width一致
绘图代码如下:
p = ggplot(dat, aes(x = type,y = Num,fill = Sample))+ geom_bar(stat ="identity",width = 0.6,position = "dodge")+ geom_errorbar(aes(ymin=(Num-SD),ymax=(Num+SD)),width=0.2,size=0.02,position = position_dodge(width = 0.6))+ scale_fill_manual(values = c("red","blue"))+ labs(x = "",y = "", title = "test")+ geom_text(aes(label = dat$Num),position=position_dodge(width = 0.5),size = 5,vjust = -0.25)+ guides(fill = guide_legend(reverse = F))+ theme(plot.title = element_text(size = 25,face = "bold", vjust = 0.5, hjust = 0.5), legend.title = element_blank(), legend.text = element_text(size = 18, face = "bold"), legend.position = 'right', legend.key.size=unit(0.8,'cm')) print(p)
读到这里,这篇“ggplot2怎么为分组柱状图添加误差线”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。