ggplot2 show separate mean values in box plot for grouped data

Jon picture Jon · May 29, 2014 · Viewed 7.9k times · Source

I would like to create a box plot for grouped data that shows the mean of each group as a point in the box. Using the following code, I only get a single point for the two groups.

df <- data.frame(a=factor(rbinom(100, 1, 0.45), label=c("m","w")), 
    b=factor(rbinom(100, 1, 0.3), label=c("young","old")),
    c=rnorm(100))
ggplot(aes(y = c, x = b, fill = a), data = df) + 
    geom_boxplot() +
    stat_summary(fun.y="mean", geom="point", shape=21, size=5, fill="white")

enter image description here

Answer

MrFlick picture MrFlick · May 29, 2014

Part of the problem was changing the fill of the point, since the fill is the property that determines that two box plots of different color should be drawn, the point behaves as if there were only one group again. I think this should give you what you want.

ggplot(df, aes(x=b, y=c, fill=a)) +
  geom_boxplot() +
  stat_summary(fun.y="mean", geom="point", size=5,
    position=position_dodge(width=0.75), color="white")

box plot with mean