Add number of observations per group in ggplot2 boxplot

You can just use position:

p <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(am))) +  
     geom_boxplot() +
     stat_summary(fun.data = give.n, geom = "text", fun.y = median,
                  position = position_dodge(width = 0.75))
p

enter image description here

The width argument of position_dodge() controls the positioning on the horizontal axis. 0.75 is the sweet spot, see how it works for different numbers of groupings:

p2 <- ggplot(mtcars, aes(factor(vs), mpg, colour = factor(cyl))) + 
      geom_boxplot() +
      stat_summary(fun.data = give.n, geom = "text", fun.y = median, 
                   position = position_dodge(width = 0.75))
p2

enter image description here

Leave a Comment