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

时间:2017-08-03 01:47:43

标签: r ggplot2 confidence-interval

其他帖子也提到了这个问题,但我还没弄清楚如何正确使用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)

1 个答案:

答案 0 :(得分:2)

一种可能的解决方案:

position = position_dodge()中添加geom_errorbar参数,并指定栏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 postthis 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')

您还可以使用widthposition_dodge()

中的geom_errorbar()参数控制误差线的位置和宽度

如果您想将错误栏居中,可能需要在width中指定geom_bar()width = 0.8(默认情况下看起来像0.9)并在{中应用相同的值在position_dodge(width = 0.8)内{1}}(如果未在geom_errorbar()中设置width,请使用0.9)。 geom_bar中的width会告诉ggplot错误条的宽度。