4

I'm trying to create a histogram of results using geom_bar and want to include the count of results as text within each bar aligned with the x-axis.

This is what i have so far:

df <- data.frame(results = rnorm(100000))

require(ggplot2)

p = ggplot(df, aes(x =  results)) 

p = p + geom_bar(binwidth = 0.5, colour = "black", fill = "white", drop = T)

p = p + scale_y_log10()

p = p + geom_hline(aes(yintercept = 1))

p = p + stat_bin(geom = "text", binwidth = 0.5,
             aes(x = results, angle = 90, y = 2, 
                 label = gsub(" ", "",format(..count.., big.mark = ",", 
                                             scientific=F)))) 

p

enter image description here

As you can see the text is not aligned with the x-axis and as my true data is far larger (in the order of millions) this problem is made slightly worse:

Current figure: enter image description here

Desired figure: enter image description here

Note: by setting y = 3 in stat_bin i get a warning stating "Mapping a variable to y and also using stat="bin". etc..." but am not sure how to force the position of the text to be at the bottom of the graph without defining a y value.

Andrie
  • 176,377
  • 47
  • 447
  • 496
Daniel Gardiner
  • 936
  • 8
  • 11
  • A side-note: when I run your code, I get an error (not a warning): "`Error : Mapping a variable to y and also using stat="bin`". ggplot2_1.0.0 – Henrik Jul 15 '14 at 09:26

1 Answers1

5

You can do this by swapping the geom and the stat. In other words, use geom_text(stat="bin", ...).

This allows you to explicitly set the y position (i.e. outside the aes) and also specify the text alignment with hjust=0.

Try this:

ggplot(df, aes(x =  results)) +
  geom_bar(binwidth = 0.5, colour = "black", fill = "white", drop = T) +
  scale_y_log10() +
  geom_hline(aes(yintercept = 1)) +
  geom_text(stat="bin", binwidth = 0.5, y=0.1, hjust=0,
           aes(x = results, angle = 90, 
               label = gsub(" ", "", format(..count.., big.mark = ",", 
                                            scientific=F)))) 

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496