Search code examples
rggplot2meanboxplot

Add mean to grouped box plot in R with ggplot2


I created a grouped box plot in R with ggplot2. However, when I want to add the mean, the dots appear between the two boxes in a group. How can I change it such that the dots are within each box?

Here my code:

ggplot(results, aes(x=treatment, y=effect, fill=sex)) + 
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red")`

Solution

  • You can use position_dodge2. Because points and boxplots have differing widths, you will need to trial and error with the width argument to centralise the dots.

    ggplot(mtcars, aes(x=factor(gear), y=hp, fill=factor(vs))) +
    geom_boxplot() +
    stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red",
                 position = position_dodge2(width = 0.75,   
                                            preserve = "single"))
    

    enter image description here