Search code examples
rggplot2facet-gridgeom-text

Annotate facet plot with grouped variables


I would like to place the numbers of observations above a facet boxplot. Here is an example:

exmp = mtcars %>% as_tibble() %>%
  mutate(cartype = as.factor(row.names(mtcars))) %>% 
  group_by(cyl, am, gear) %>% 
  mutate(N = n())

ggplot(exmp, aes(x = am, fill = gear, y = wt)) +
  facet_grid(.~cyl) +
  geom_boxplot() +
  geom_text(aes(y = 6, label = N))

So, I already created column N to get the label over each box in the boxplot (combination of cyl, am and gear). How do I plot these labels so that they are over the respective box? Please note that the number of levels of gear for each level of am differs on purpose.

I really looked at a lot of ggplot tutorials and there are tons of questions dealing with annotating in facet plots. But none addressed this fairly common problem...enter image description here


Solution

  • You need to give position_dodge() inside geom_textto match the position of the boxes, also define data argument to get the distinct value of observations:

    ggplot(exmp, aes(x = as.factor(am), fill = as.factor(gear), y = wt)) +
      geom_boxplot() +
      facet_grid(.~cyl) + 
      geom_text(data = dplyr::distinct(exmp, N), 
                aes(y = 6, label = N), position = position_dodge(0.9))
    

    enter image description here