Search code examples
rggplot2boxplot

Add a number of observations per group AND SUBGROUP in ggplot2 boxplot


This might seem like a duplicate of this question, but in fact I want to expand the original question.

I want to annote the boxplot with the number of observations per group AND SUBGROUP in ggplot. Following the example or the original post, here is my minimal example:

require(ggplot2)

give.n <- function(x){
  return(c(y = median(x)*1.05, label = length(x))) 
  # experiment with the multiplier to find the perfect position
}

ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
  geom_boxplot() +
  stat_summary(fun.data = give.n, geom = "text", fun.y = median)

My problem is that the number of samples all line up in the center of the group, rather than plotting on the appropriate boxplot (as the picture below shows):Annotes are centering in the middle of the group rather than plotting on the appropriate boxplot


Solution

  • is it what you want?

    require(ggplot2)
    
    give.n <- function(x){
      return(c(y = median(x)*1.05, label = length(x))) 
      # experiment with the multiplier to find the perfect position
    }
    
    ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(gear))) +
      geom_boxplot() +
      stat_summary(fun.data = give.n, geom = "text", fun.y = median, position=position_dodge(width=0.75))
    

    enter image description here