views:

369

answers:

4

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?

+1  A: 

If you are not restricted to ggplot2, you could use ?text from base graphics or ?boxed.labels from the plotrix package.

Karsten W.
+2  A: 

A hard way to do it. I'm sure there are better approaches.

ggplot(mtcars,aes(factor(cyl))) + 
geom_bar() + 
geom_text(aes(y=sapply(cyl,function(x) 1+table(cyl)[names(table(cyl))==x]),
label=sapply(cyl,function(x) table(cyl)[names(table(cyl))==x])))
gd047
It's generally good practice to create your data _outside_ of your plotting code. And it is _never_ a good idea to shove data into the aesthetic mappings.
hadley
+4  A: 

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.

Aniko
Thank you so much for this one! It does exactly the thing I wanted!
aL3xa
A: 

When wanting to add different info the following works:

ggplot(mydata, aes(x=clusterSize, y=occurence)) +
geom_bar() + geom_text(aes(x=clusterSize, y=occurence, label = mydata$otherinfo))
Yannick Wurm
Can you, please, replicate this answer by providing an example that refers to data available in `datasets` package (or other package available in CRAN repos)? I doubt that barplot can be drawn with `y` variable specified "as is"...
aL3xa