Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show frequencies along with barplot in ggplot2

Tags:

I'm trying to display frequencies within barplot ... well, I want them somewhere in the graph: under the bars, within bars, above bars or in the legend area. And I recall (I may be wrong) that it can be done in ggplot2. This is probably an easy one... at least it seems easy. Here's the code:

p <- ggplot(mtcars)
p + aes(factor(cyl)) + geom_bar()

Is there any chance that I can get frequencies embedded in the graph?

like image 315
aL3xa Avatar asked Mar 31 '10 10:03

aL3xa


1 Answers

geom_text is tha analog of text from base graphics:

p + geom_bar() + stat_bin(aes(label=..count..), vjust=0, 
                          geom="text", position="identity")

If you want to adjust the y-position of the labels, you can use the y= aesthetic within stat_bin: for example, y=..count..+1 will put the label one unit above the bar.

The above also works if you use geom_text and stat="bin" inside.

like image 82
Aniko Avatar answered Sep 20 '22 17:09

Aniko