Search code examples
rggplot2histogram

How to show count of each bin on histogram on the plot


I figured out how to get the count of each bin from ggplot, does anyone know how to show these numbers on the plot?

g <- ggplot()+geom_histogram()
ggplot_build(g)$data[[1]]$count

Solution

  • You can add a stat_bin to do the calculations of counts for you, and then use those values for the labels and heights. Here's an example

    set.seed(15)
    dd<-data.frame(x=rnorm(100,5,2))
    ggplot(dd, aes(x=x))+ geom_histogram() +
        stat_bin(aes(y=..count.., label=..count..), geom="text", vjust=-.5) 
    

    labeled histogram