ggplot绘制带误差棒的分组柱状图时新增元素即报mapping需由aes()创建错误的咨询
问题原因
报错本质是函数嵌套逻辑错误:labs()、facet_wrap()是ggplot2体系下的独立全局配置/图层函数,不属于geom_bar()的合法入参。你将这类函数直接写在geom_bar()的括号内部,相当于给geom_bar()传递了不符合类型要求的参数,最终触发mapping must be created by aes()的报错。
错误逻辑示意
geom_bar( stat="identity", color="black", position=position_dodge(), # 非法嵌套在geom_bar参数列表中的内容 labs(title = "Corticosterone"), facet_wrap(~Sex) )
修复方案
将所有非geom_bar()入参的配置项、独立图层移出geom_bar()的括号范围,按照ggplot2的图层拼接规则,用+与原有绘图元素平级连接即可:
- 带标题的修正后代码
p <- ggplot(corttestunitedcol, aes(x=Sex, y=mean, fill=Treatment_Status)) + geom_bar(stat="identity", color="black", position=position_dodge()) + # 独立调用labs,与其他绘图元素平级 labs(title = "Corticosterone", y = "mean plasma Corticosterone (pg/ml)", x = "") + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2, position=position_dodge(.9))
- 带分面的修正后代码
p <- ggplot(corttestunitedcol, aes(x=Sex, y=mean, fill=Treatment_Status)) + geom_bar(stat="identity", color="black", position=position_dodge()) + # 独立调用facet_wrap,与其他绘图元素平级 facet_wrap(~Sex) + geom_errorbar(aes(ymin=mean-sd, ymax=mean+sd), width=.2, position=position_dodge(.9))
注意:ggplot2的所有图层、配置项都是平级的拼接关系,凡是用+连接的元素,都不能嵌套在其他绘图函数的入参列表中,否则极易触发参数类型不匹配的各类报错。
内容的提问来源于stack exchange,提问作者DS14
相关产品推荐
相关产品推荐

