将误差线与条形图因子水平对齐

时间:2019-01-21 12:24:28

标签: r ggplot2

我正在尝试绘制带有多个误差线的条形图,这些误差线与x轴上每个因子水平的相关值对齐。

我已按照Grouped barplot in R with error bars的说明进行操作-但我无法弄清楚为什么我的脚本不配合。

这是我得到的结果,很明显,我希望误差条与相关数据保持一致。

enter image description here

这是我的数据:

structure(list(key = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("2030", "2050", "2100"
), class = "factor"), value = c(0.4, 0.4, 0.1, 0.1, 0.1, 3.4, 
4.5, 6.8, 3.6, 3, 5.7, 12.4, 14.9, 9.5, 10.8), scenario = structure(c(4L, 
2L, 1L, 6L, 5L, 4L, 2L, 1L, 6L, 5L, 4L, 2L, 1L, 6L, 5L), .Label = c("1.5°C-high-OS", 
"1.5°C-limited-OS", "1.5°C-low-OS", "Below-1.5°C", "Higher-2°C", 
"Lower-2°C"), class = "factor"), Lower.Quartile = c(0, 0, 0, 
0, 0, 0, 3.4, 3.7, 1.8, 1.6, 0, 6.4, 12.1, 6.9, 8.2), Upper.Quartile = c(1.1, 
1, 0.4, 0.3, 0.2, 8.3, 6.3, 9.5, 4.6, 4.9, 13.4, 15, 16.3, 12.1, 
15.3)), row.names = c(1L, 3L, 4L, 5L, 6L, 7L, 9L, 10L, 11L, 12L, 
13L, 15L, 16L, 17L, 18L), class = "data.frame")

这是我的代码:

library(ggplot2)
library(tidyr)    

ggplot(Global.BECCS.mean, aes(x = key)) + geom_bar(aes(fill = scenario, y = value), position = position_dodge(), stat='identity', col = "black") + theme_classic() +
      xlab('Year') + ylab(expression(paste(GtC,' sequestered by BECCS per year'))) + geom_hline(yintercept = 5.5, linetype = 'dashed') + geom_hline(yintercept = 16, linetype = 'dotted') +
      geom_errorbar(aes(ymin = Global.BECCS.mean$Lower.Quartile, ymax = Global.BECCS.mean$Upper.Quartile), width = 0.1, position = position_dodge())

1 个答案:

答案 0 :(得分:1)

几件事:

  • 在ggplot中定义yfill的美感,以允许所有层也继承它们
  • width中指定position_dodge,以使条形处于所需位置
  • 最后,我认为不需要使用Global.BECCS.mean$,变量名就足够了。

ggplot(Global.BECCS.mean, aes(x = key, fill = scenario, y = value)) + 
  geom_bar(position = position_dodge(), stat='identity', col = "black") + 
  theme_classic() +
  xlab('Year') + 
  ylab(expression(paste(GtC,' sequestered by BECCS per year'))) + 
  geom_hline(yintercept = 5.5, linetype = 'dashed') + 
  geom_hline(yintercept = 16, linetype = 'dotted') +
  geom_errorbar(aes(ymin = Lower.Quartile, 
                    ymax = Upper.Quartile), 
                width = 0.3, 
                position = position_dodge(0.9))

enter image description here

相关问题