1

This seem like a simple question, but I can't find out the answer anywhere.

Plotting a histogram, and wanting to add the data labels for the bins. This is as far as I have managed to get and the awful looking result (code is fully reproducible):

df=data.frame(ToothGrowth)
require(ggplot2)
ggplot(data=df, aes(x=len, y=..count.., label=..count..))+
        geom_histogram(binwidth=5, aes(fill=..count..))+
        geom_text(stat="bin", vjust=-1)

The resulting chart:

enter image description here

How do I fix the data labels so that they are:

1) Showing up above each of the bins?

2) Showing the counts for the bins?

vashts85
  • 1,069
  • 3
  • 14
  • 28
  • Please see the accepted answer of this SO post: http://stackoverflow.com/questions/9317948/how-to-label-histogram-bars-with-data-values-or-percents-in-r – Special Sauce Jun 21 '15 at 04:14
  • @LegalizeIt Agreed, but it is even simpler and likely meets the OP's needs. vashts85, please let us know if you are dead set on using `ggplot2` package for whatever reason. – Special Sauce Jun 21 '15 at 04:17
  • I really want to be able to do facets with this (I omitted it from the question)....is there a way to add this to the solution? – vashts85 Jun 21 '15 at 04:28
  • 2
    From duplicate question: `ggplot(df,aes(x= len)) + stat_bin(binwidth=5, aes(fill=..count..)) + stat_bin(binwidth=5, geom="text", aes(label=..count..), vjust=-1.5) + ylim(0,15)` – MrFlick Jun 21 '15 at 04:55
  • This works, except I have labels for 0 counts, and I get an error that reads: ymax not defined: adjusting position using y instead Any way to fix this? – vashts85 Jun 21 '15 at 05:02
  • another, rather crude way is to use `ggplot_build()` to access the counts: `p <- ggplot(data=df, aes(x=len, y=..count..)) + geom_histogram(binwidth=5, aes(fill=..count..)) ; p + geom_text(data=subset(ggplot_build(p)$data[[1]], count>0), aes(x,y,label=count), vjust=-1)` – user20650 Jun 21 '15 at 05:08

0 Answers0