Search code examples
rggplot2histogramfacet-grid

Adding total histogram count to facets in ggplot in R


I would like to take a faceted histogram and add text on each plot indicating the total number of observations in that facet. So for carb = 1 the total count would be 7, carb = 2 the total count would be 10 etc.

p <- ggplot(mtcars, aes(x = mpg, stat = "count",fill=as.factor(carb))) + geom_histogram(bins = 8)
p <- p + facet_grid(as.factor(carb) ~ .)
p

I can do this with the table function but for more complex faceting how can I do it quickly?

enter image description here


Solution

  • You can try this. Maybe is not the most optimal because you have to define the x and y position for the label (this is done in Labels for x and in geom_text() for y with 3). But it can help you:

    #Other
    library(tidyverse)
    #Create similar data for labels
    Labels <- mtcars %>% group_by(carb) %>% summarise(N=paste0('Number is: ',n()))
    #X position
    Labels$mpg <- 25
    #Plot
    ggplot(mtcars, aes(x = mpg, stat = "count",fill=as.factor(carb))) + geom_histogram(bins = 8)+
      geom_text(data = Labels,aes(x=mpg,y=3,label=N))+facet_grid(as.factor(carb) ~ .)
    

    enter image description here