ggplot绘制多参数分组条形图遇stat_bin报错,求解决方案
解决ggplot2中stat_bin()与y aesthetic冲突的问题
嘿,这个问题我之前也碰到过!咱们来一步步拆解解决:
错误原因
你遇到的Error: stat_bin() must not be used with a y aesthetic是因为geom_histogram的设计逻辑就是自动统计x轴数据的频数/频率,它会自动生成y轴的计数结果,所以你手动传入Award_USD作为y轴参数就会冲突。而你想要的是展示具体金额的分组/堆叠条形图,应该用geom_bar而非geom_histogram。
修正后的代码
根据你的需求(按Office_abb展示Award_USD,按Region分组/堆叠),这里提供两种方案:
1. 分组并排条形图(dodge样式)
My_df %>% filter(Context == "Humanitarian") %>% ggplot(aes(x = Office_abb, y = Award_USD, color = Region, fill = Region)) + geom_bar(stat = "identity", position = position_dodge2(preserve = "single")) + # position_dodge2更适配不等长分组 theme(legend.position = "bottom") + ggtitle("Overview of office amount pr. region") + theme(axis.text.x = element_text(angle = 90, hjust = 1))
2. 堆叠条形图
如果想要堆叠样式,只需要把position参数改成"stack"即可:
My_df %>% filter(Context == "Humanitarian") %>% ggplot(aes(x = Office_abb, y = Award_USD, color = Region, fill = Region)) + geom_bar(stat = "identity", position = "stack") + theme(legend.position = "bottom") + ggtitle("Overview of office amount pr. region") + theme(axis.text.x = element_text(angle = 90, hjust = 1))
关键说明
stat = "identity":这个参数告诉ggplot直接使用你传入的y轴数值(Award_USD),而不是默认的统计频数。position_dodge2(preserve = "single"):相比普通的position="dodge",它能更好地处理某些Office_abb下缺少部分Region数据的情况,避免条形图错位。
内容的提问来源于stack exchange,提问作者BloopFloopy
相关产品推荐
相关产品推荐

