24

Below code works well and it labels the barplot correctly, However, if I try geom_text for a histogram I fail since geom_text requires a y-component and a histogram's y component is not part of the original data.

Label an "ordinary" bar plot (geom_bar(stat = "identity") works well:

 ggplot(csub, aes(x = Year, y = Anomaly10y, fill = pos)) +
        geom_bar(stat = "identity", position = "identity") +
        geom_text(aes(label = Anomaly10y,vjust=1.5))  

My Problem: How to get the correct y and label (indicated by ?) for geom_text, to put labels on top of the histogram bars

ggplot(csub,aes(x = Anomaly10y)) + 
        geom_histogram() 
        geom_text(aes(label = ?, vjust = 1.5))

geom_text requires x, y and labels. However, y and labels are not in the original data, but generated by the geom_histogram function. How can I extract the necessary data to position labels on a histogram?

Henrik
  • 65,555
  • 14
  • 143
  • 159
Shoaibkhanz
  • 1,942
  • 3
  • 24
  • 41

2 Answers2

51

geom_histogram() is just a fancy wrapper to stat_bin so you can all that yourself with the bars and text that you like. Here's an example

#sample data
set.seed(15)
csub<-data.frame(Anomaly10y = rpois(50,5))

And then we plot it with

ggplot(csub,aes(x=Anomaly10y)) + 
    stat_bin(binwidth=1) + ylim(c(0, 12)) +  
    stat_bin(binwidth=1, geom="text", aes(label=..count..), vjust=-1.5) 

to get

labeled univariate ggplot2 barplot

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    As a side note, adding `+ limits(x=c(0, 12))` will show the label for 10. – tonytonov Jun 13 '14 at 06:33
  • 1
    @tonytonov I should have done that. I went ahead and updated the example to extend the range so no labels are cut off. – MrFlick Jun 13 '14 at 06:40
  • Thanks, Its working, however, it is throwing a warning: "ymax not defined: adjusting position using y instead." – Shoaibkhanz Jun 13 '14 at 10:32
  • For factor histograms one needs to use `+ stat_count(binwidth=1, geom="text", aes(label=..count..), vjust=0.25)` just if anyone has the same question for this case... – mhwh Mar 07 '18 at 11:15
7

Ok to make it aesthetically appealing here is the solution:

set.seed(15)
csub <- data.frame(Anomaly10y = rpois(50, 5))

Now Plot it

csub %>%
  ggplot(aes(Anomaly10y)) +
  geom_histogram(binwidth=1) +
  stat_bin(binwidth=1, geom='text', color='white', aes(label=..count..),
           position=position_stack(vjust = 0.5))

resultant plot will be

enter image description here

Arun Kumar Khattri
  • 1,519
  • 15
  • 25