Search code examples
rggplot2r-markdownhistogramknitr

How to print Frequencies on top of Histogram bars in ggplot


I would like to know if it is possible to display the frequencies at the top of each counting bar in a ggplot histogram.

This is the code I have got so far:

br <- seq(0, 178, 10)
ggplot(dfAllCounts, aes(x=months)) + geom_histogram(aes(months), bins = 30, fill="#d2aa47", color = '#163B8B', size = .8, alpha = 0.3) + 
  scale_x_continuous(breaks = br)

I would like to display that number of months on top, thanks


Solution

  • Instead of the geom_histogram wrapper, switch to the underlying stat_bin function, where you can use the built in geom="text", combined with the after_stat(count) to add the label to a histogram.

    ggplot(mpg,aes(x=displ)) + 
      stat_bin(binwidth=1) +
      stat_bin(binwidth=1, geom="text", aes(label=after_stat(count)), vjust=0) 
    

    Modified from https://stackoverflow.com/a/24199013/10276092