简体   繁体   中英

ggplot2 - How to center confidence interval bars on bar plot

this has been asked on other posts, but I have not figured out how to use position_dodge correctly.

How can I center each CI bar in each bar on the graph?

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)

One possible solution:

Add position = position_dodge() argument in your geom_errorbar and specify your bar 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)

After some searching (eg this post and this page ), the code can be further improved,

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')

You can also control the position and width of the error bars using the width argument in position_dodge() and geom_errorbar()

If you want to center the error bars, you may need to specify the width in geom_bar() say width = 0.8 (looks like 0.9 is the default) and apply the same value in position_dodge(width = 0.8) inside geom_errorbar() (use 0.9 if you don't set the width in geom_bar ). And width in geom_errorbar will tell ggplot the width of the error bars.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM