Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put labels over geom_bar in R with ggplot2

Tags:

r

ggplot2

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?

like image 966
angerman Avatar asked Jun 23 '11 13:06

angerman


People also ask

What is the difference between Geom_col and Geom_bar?

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.

How do I add percentages to a Barplot in R?

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.


1 Answers

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() ) 

enter image description here

like image 154
Andrie Avatar answered Sep 23 '22 17:09

Andrie