Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 485
melani Avatar asked Dec 14 '25 14:12

melani


1 Answers

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

like image 161
Duck Avatar answered Dec 16 '25 22:12

Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!