How to put labels above geom_bar in R using ggplot2

I would like some labels to be laid on top of the geom_bar graph. Here is 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 would like to have 3 and 5 on top of two bars. Even better if I had percentage values. For example. 3 (37.5%) and 5 (62.5%) . Like this:

Is it possible? If so, how?

+33
r ggplot2
Jun 23 2018-11-11T00:
source share
2 answers

As with many tasks in ggplot, the overall strategy is to add what you want to add to the graph in the data frame so that the variables match the variables and aesthetics in your plot. For example, you should create a new data frame, for example:

 dfTab <- as.data.frame(table(df)) colnames(dfTab)[1] <- "x" dfTab$lab <- as.character(100 * dfTab$Freq / sum(dfTab$Freq)) 

So, the variable x corresponds to the corresponding variable in df , etc. Then you just turn it on using geom_text :

 ggplot(df) + geom_bar(aes(x,fill=x)) + geom_text(data=dfTab,aes(x=x,y=Freq,label=lab),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()) 

In this example, only percentages will be displayed, but you can paste together counting also through something like this:

 dfTab$lab <- paste(dfTab$Freq,paste("(",dfTab$lab,"%)",sep=""),sep=" ") 

Please note that in the current version of ggplot2 opts deprecated, so we will now use theme and element_blank .

+28
Jun 23 '11 at 1:59 april
source share

To build text on ggplot , geom_text used. But I find it useful to generalize the data first using ddply

 dfl <- ddply(df, .(x), summarize, y=length(x)) str(dfl) 

Since the data is pre-summed, you need to remember to 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

+32
Jun 23 2018-11-11T00:
source share



All Articles