如何用R的ggplot2绘制X轴两侧分属正负Y轴的柱状图
要实现ER在Y轴正区间向上展示、GEP在Y轴负区间向下展示的合并双向柱状图,直接在同一个ggplot对象中叠加两组图层即可,核心是将GEP的Y值取负映射,对应代码如下:
library(ggplot2) combined.2015.bar <- ggplot(Salix_data.2015, aes(x = Flux_Date, fill = Treatment)) + # 叠加ER正向图层 stat_summary(aes(y = ER), fun=mean, geom="bar", position="dodge", width =0.8, alpha = 0.8) + stat_summary(aes(y = ER), fun.data = mean_se, geom = "errorbar", width=0.2, position = position_dodge(0.8)) + # 叠加GEP负向图层,y取负实现向下展示 stat_summary(aes(y = -GEP), fun=mean, geom="bar", position="dodge", width =0.8, alpha = 0.5) + stat_summary(aes(y = -GEP), fun.data = mean_se, geom = "errorbar", width=0.2, position = position_dodge(0.8)) + # ER显著性标注,和原有逻辑一致 annotate(geom = "text", x = 1, y = 8000, label = "a")+ annotate(geom = "text", x = 2, y = 5000, label = "a")+ annotate(geom = "text", x = 3, y = 7500, label = "b")+ annotate(geom = "text", x = 3, y = 8000, label = "*")+ annotate(geom = "text", x = 4, y = 3000, label = "a")+ # GEP显著性标注,y保持负向即可 annotate(geom = "text", x = 1, y = -20000, label = "a")+ annotate(geom = "text", x = 2, y = -12000, label = "b")+ annotate(geom = "text", x = 3, y = -17000, label = "a")+ annotate(geom = "text", x = 4, y = -10000, label = "a")+ annotate(geom = "text", x = 3, y = -19000, label = "*")+ # Y轴标签转换,负区间显示GEP绝对值避免阅读混淆 scale_y_continuous(labels = function(x) ifelse(x<0, -x, x), name = "ER / GEP") + # 主题与标题设置 theme(legend.position = "bottom") + labs(title = "2015年北极柳灌丛ER与GEP按日期和处理分组对比", x="日期") print(combined.2015.bar)
可调整细节
- 代码中用alpha透明度区分两类指标的柱子,你也可以取消alpha参数,或者修改fill映射规则为
fill = interaction(Treatment, 指标类型),用不同色系直接区分ER和GEP - 如需分别设置两个指标的Y轴标签,可添加次轴配置:
scale_y_continuous(..., sec.axis = sec_axis(~.*-1, name = "GEP")),主Y轴对应ER,次Y轴对应GEP
内容的提问来源于stack exchange,提问作者user16900506
相关产品推荐
相关产品推荐

