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 .
joran Jun 23 '11 at 1:59 april 2011-06-23 13:59
source share