I'd like to have some labels stacked on top of a geom_bar
graph. Here's an example:
df <- data.frame(x=factor(c(TRUE,TRUE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE))) ggplot(df) + geom_bar(aes(x,fill=x)) + opts(axis.text.x=theme_blank(),axis.ticks=theme_blank(),axis.title.x=theme_blank(),legend.title=theme_blank(),axis.title.y=theme_blank())
Now
table(df$x)
FALSE TRUE 3 5
I'd like to have the 3 and 5 on top of the two bars. Even better if I could have the percent values as well. E.g. 3 (37.5%)
and 5 (62.5%)
. Like so:
(source: skitch.com)
Is this possible? If so, how?
geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.
A better way to make the barplot is to add the percentage symbol on the y-axis instead of the fraction we have now. We can use scales package' percent method to add percentage symbol to the y-axis using scale_y_continuous() function. Now our y-axis text has percentage symbols in the barplot.
To plot text on a ggplot
you use the geom_text
. But I find it helpful to summarise the data first using ddply
dfl <- ddply(df, .(x), summarize, y=length(x)) str(dfl)
Since the data is pre-summarized, you need to remember to change add the stat="identity"
parameter to geom_bar
:
ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") + geom_text(aes(label=y), vjust=0) + opts(axis.text.x=theme_blank(), axis.ticks=theme_blank(), axis.title.x=theme_blank(), legend.title=theme_blank(), axis.title.y=theme_blank() )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With