ggplot2 - Bars non-aligned to error bars

前端 未结 1 2058
野趣味
野趣味 2021-01-15 00:34

I am trying to plot error bars over bars in R using ggplot2. The position of the bars is ok, however the error bars are misaligned, overlapped. Please take a look at the exa

1条回答
  •  伪装坚强ぢ
    2021-01-15 01:10

    You should add group = variable inside the aes() of ggplot() to make position_dodge() work.

    ggplot(data=df, aes(x=Period, y=value, group = variable)) +
          geom_bar(aes(fill=variable), position='dodge', stat="identity", width=0.75) +
          geom_errorbar(aes(ymin=ymin, ymax=ymax), position = position_dodge(0.75),width = 0.2) +
          facet_wrap(~scenario) +
          theme_bw(base_size=16)
    

    The same can be atchieved if you move the fill = variable to the aes() of ggplot() from geom_bar().

    ggplot(data=df, aes(x=Period, y=value, fill = variable)) +
          geom_bar(position='dodge', stat="identity", width=0.75) +
          geom_errorbar(aes(ymin=ymin, ymax=ymax), position = position_dodge(0.75),width = 0.2) +
          facet_wrap(~scenario) +
          theme_bw(base_size=16)
    

    0 讨论(0)
提交回复
热议问题