Search code examples
rggplot2position

Centering stat_summary errorbars with position_dodge2


I can't seem to get these errorbars to center on the bars. I thought position_dodge2(width=0.5) would do the trick but changing the width argument doesn't seem to do anything?
Example:

    set.seed(1234)
    library(tidyverse)
    data.frame(rep=c(rep(1,15),rep(2,15)),
               num=rep(c(sample(c(1:15),15)),2),
               sex=rep(c(sample(c("m","f"),15,T))),
               conc=rep(c(rep("1:1000",5),rep("1:100",5),rep("1:10",5)),2),
               c1=c(sample(c(0:100),15,T),sample(c(0:100),15,T)),
               c2=c(sample(c(0:100),15,T),sample(c(0:100),15,T)),
               c3=c(sample(c(0:100),15,T),sample(c(0:100),15,T)),
               c4=c(sample(c(0:100),15,T),sample(c(0:100),15,T)))%>%
      pivot_longer(cols=c(c1,c2,c3,c4),
                   names_to="compound",
                   values_to="time")%>%
      ggplot(aes(x=compound,
                 y=time,
                 group=rep,
                 fill=as.factor(rep)))+
      stat_summary(fun="mean",geom="col",
                   position=position_dodge2(width=1))->p1
    p1+facet_grid(conc~.)
    p1+stat_summary(fun.data="mean_se",geom="errorbar",
                    width=0.5,
                    position=position_dodge2(width=0.5))+
      facet_grid(conc~.)
    p1+stat_summary(fun.data="mean_se",geom="errorbar",
                    width=0.5,
                    position=position_dodge2(width=1))+
      facet_grid(conc~.)
    p1+stat_summary(fun.data="mean_se",geom="errorbar",
                    width=0.5,
                    position=position_dodge2(width=0.1))+
      facet_grid(conc~.)
    p1+stat_summary(fun.data="mean_se",geom="errorbar",
                    width=0.5,
                    position=position_dodge(width=0.5))+
      facet_grid(conc~.)

Solution

  • I believe this is a bug in position_dodge2() for dodging error bars, as I've encountered the same issue. Dodging point geoms with position_dodge2() is similarly finnicky.

    The fix would be to use position_dodge(), although you may have to play around a bit with the dodge with and the width of the geom itself to get things looking right:

    p1 + stat_summary(fun.data="mean_se",geom="errorbar",
                    width=0.5,
                    position=position_dodge(width=0.9)) +
        facet_grid(conc~.)
    

    enter image description here