您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。