Problem placing error bars at the center of the columns in ggplot()

若如初见. 提交于 2019-12-04 09:42:57

Nice question. A couple of comments:

  1. In general, it's a good practice to set all your aesthetics in the original ggplot() call, and to override them with different aesthetics only if needed in the individual geom_xyz() calls. In your code, you were setting the fill aesthetic twice, once in ggplot and once in geom_bar. You also set the group aesthetic in geom_errorbar(). I don't think any of those things were the ultimate problem, but they did make it harder to debug your code.

  2. The main problem was that the width argument in geom_bar has to match the position_dodge() argument inside geom_errorbar. So if you have

    # ...
    geom_bar(stat = "identity", position = "dodge", width = 0.5)
    # ...
    

    Then you've got to make sure your geom_errorbar() looks like

    # ...
    geom_errorbar(width = .08, position = position_dodge(0.5)) 
    # ...
    

Putting it all together:

require(ggplot2)
require(scales)

# define data
a <- data.frame (Cond = c("In", "In", "Out", "Out"),
                Temp = c("Hot", "Cool", "Hot", "Cool"),
                Score = c(.03, -.15, 0.84, 0.25),
                SE = c(.02, .08, .14, .12))

# return plot with everything except error bars
a.bar <- ggplot (data = a, aes(x = Cond, 
                               y = Score, 
                               fill = Temp,
                               ymin = Score - SE,
                               ymax = Score + SE)) +
            theme_bw() + 
            theme(panel.grid = element_blank ()) +
            coord_cartesian(ylim = c(-0.5, 1)) + 
            # manually setting the width means we will have to tell geom_errorbar() about the new width
            geom_bar(stat = "identity", position = "dodge", width = 0.5) + 
            labs(y = "Scores", x = "Cond") +
            scale_y_continuous(breaks = pretty_breaks(n = 8)) +
            theme(legend.title = element_blank()) +
            theme(legend.position = "right")

# show plot w/ errorbars, note that argument to position_dodge is same as width supplied above
a.bar + geom_errorbar(width = .08, position = position_dodge(0.5)) 

# save results
ggsave('SO_35424162.png')

Clément Goubert

I would like to add, since I ran into the same issue:

It is very important to specify the fill parameter in the main aes() and not in the geom_barplot.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!