geom_bar与geom_errorbar仅单组条形显示误差棒问题排查
问题:ggplot分组条形图误差棒错位
你有如下结构的DataFrame:
structure(list(type = c("aerial", "aerial", "aerial", "aerial", "TLAcmeth", "TLAcmeth", "TLAcmeth", "TLAcmeth", "TLAmeandaily", "TLAmeandaily", "TLAmeandaily", "TLAmeandaily"), season = c("Fall", "Spring", "Summer", "Winter", "Fall", "Spring", "Summer", "Winter", "Fall", "Spring", "Summer", "Winter"), TotalEffort = c(190673.543181818, 218904.879166667, 203450.11969697, 56238.5424242424, 268342.820454545, 285751.855555556, 345593.292424242, 98186.1393939394, 231709.359979371, 240226.110903571, 297768.291682299, 89965.0324616366), TotalVariance = c(492915253.434218, 568040077.261171, 647316950.988574, 98882407.0742865, 1809446616.57252, 1459917672.26073, 2412306298.47967, 249200347.968292, 690088788.630394, 219887023.857297, 762532238.93411, 184763903.639171), STE = c(22201.6948324721, 23833.5913630567, 25442.424235685, 9943.96334839819, 42537.5906296128, 38208.8690261924, 49115.2348918304, 15786.0808299049, 26269.5410814577, 14828.588060139, 27613.9862919882, 13592.7886630806)), row.names = c(NA, -12L), class = "data.frame")
使用这段ggplot代码绘图时:
ggplot(E_StE, aes(x = season, y = TotalEffort, fill = type)) + geom_bar(stat = "identity", position = "dodge", color = "black") + scale_y_continuous(name = "Estimated Effort (h)", expand = c(0, 0)) + geom_errorbar(aes(ymin = TotalEffort-STE, ymax = TotalEffort+STE), position = "dodge", width = 0.2) + xlab("Season")
出现的问题是所有误差棒只显示在一组条形上,没有对应到各自的分组条形。
解决方案
问题出在geom_errorbar的位置设置上:geom_bar默认的position = "dodge"使用的宽度是0.9,但你给geom_errorbar只写了position = "dodge",没有指定匹配的宽度,导致误差棒的偏移位置和条形不对齐,全部堆到了同一组。
修正方法是把geom_errorbar的位置设置改成position = position_dodge(width = 0.9),手动指定和条形一致的dodge宽度,这样误差棒就会和对应分组的条形对齐。
修正后的完整代码:
ggplot(E_StE, aes(x = season, y = TotalEffort, fill = type)) + geom_bar(stat = "identity", position = position_dodge(width = 0.9), color = "black") + scale_y_continuous(name = "Estimated Effort (h)", expand = c(0, 0)) + geom_errorbar(aes(ymin = TotalEffort - STE, ymax = TotalEffort + STE), position = position_dodge(width = 0.9), width = 0.2) + xlab("Season")
运行这段代码后,每个分组条形都会对应自己的误差棒,不会再出现错位的情况。
内容的提问来源于stack exchange,提问作者Ryan Gary
相关产品推荐
相关产品推荐

