ggplot2 - 如何在条形图上居中置信区间条

ggplot2 - How to center confidence interval bars on bar plot

其他帖子也有人问过这个问题,但我还没弄清楚如何正确使用position_dodge

如何让每个 CI 条在图表的每个条中居中?

df <- structure(list(Ano = c(2012, 2012, 2012, 2016, 2016, 2016), 
               Grupo = c("Controle", "Tratado", "Total", 
                         "Controle", "Tratado", "Total"), 
               Margem_Mediana = c(4.4,3.1, 4.2, 3.8, 2.5, 3.6), 
               Erro_Padrao = c(0.0236, 0.0460, 0.0214, 0.0257, 0.0478, 0.0231)), 
          class = c("tbl_df", "tbl", "data.frame"), 
          row.names = c(NA, -6L), .Names = c("Ano", "Grupo", "Margem_Mediana", "CI"))


ggplot(df, aes(x = Ano, y = Margem_Mediana, fill = Grupo)) +
  geom_bar(data = subset(df, Grupo != 'Total'),
                         position = position_dodge(), stat = 'identity') +
  geom_errorbar(data = subset(df, Grupo != 'Total'),
                              aes(ymin = Margem_Mediana - CI,
                    ymax = Margem_Mediana + CI),
                width = 1.5,
                size = 0.5)

一种可能的解决方案:

在您的 geom_errorbar 中添加 position = position_dodge() 参数并指定您的栏 width.

ggplot(df, aes(x = Ano, y = Margem_Mediana, fill = Grupo)) +
  geom_bar(data = subset(df, Grupo != 'Total'),
           width = 1.5, 
           position = position_dodge(), 
           stat = 'identity') +
  geom_errorbar(data = subset(df, Grupo != 'Total'),
                aes(ymin = Margem_Mediana - CI,
                    ymax = Margem_Mediana + CI),
                width = 1.5,
                position = position_dodge(),
                size = 0.5)

经过一番搜索(例如this post and this page),代码可以进一步改进,

ggplot(subset(df, Grupo != 'Total'), 
       aes(x = as.factor(Ano), y = Margem_Mediana, fill = Grupo)) +
    geom_bar(width = 0.8, 
             position = position_dodge(), 
             stat = 'identity') +
    geom_errorbar(aes(ymin = Margem_Mediana - CI,
                      ymax = Margem_Mediana + CI), 
                  width = 0.4, 
                  position = position_dodge(width = 0.8)) + 
    xlab('Ano')

您还可以使用 position_dodge()geom_errorbar()

中的 width 参数控制误差线的位置和宽度

如果你想将错误栏居中,你可能需要在 geom_bar() 中指定 widthwidth = 0.8(看起来 0.9 是默认值)并应用相同的值在 geom_errorbar() 中的 position_dodge(width = 0.8) 中(如果不在 geom_bar 中设置 width,则使用 0.9)。 geom_errorbar 中的 width 会告诉 ggplot 误差线的宽度。