-2

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
Jaap
  • 81,064
  • 34
  • 182
  • 193
PhoenixQ
  • 123
  • 1
  • 2
  • 5
  • Use `stat_bin` with `geom_text`. – Roland May 20 '14 at 19:46
  • Welcome to StackOverflow! Please read the info about how to [ask a question](http://stackoverflow.com/help/how-to-ask) and how to produce a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) – Jaap May 20 '14 at 20:06

1 Answers1

24

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

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 4
    what if you only want to show those that are non-zero? – Yannick Wurm Aug 06 '18 at 23:49
  • 4
    quick n' dirty way to remove zeroes: aes(y=..count.., label=ifelse(..count..==0,"",..count..) – Jinglestar Apr 08 '21 at 11:00
  • 1
    Just an update for 2023 readers, using this does still work, but replace each instance of the `..count..` with `after_stat(count)`. "The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0. i Please use `after_stat(count)` instead." – pseudorandom May 30 '23 at 19:39