Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Bar charts and histograms are easily to understand. I often write for non-specialist audiences so I tend to use them a lot. People like percentages too, so a bar chart with counts on the y axis but percentage labels is a useful thing to be able to produce.

But how to do them in our graphics package of choice, ggplot? ggplot makes histograms by doing a stat transformation, stat_bin. Not sure whether this is a good design decision, rather than requiring the user to bin the data first, because it is harder to customise stat_bin to get what you want, in this case percentage labels.

 library(ggplot2) library(scales) perbar=function(xx){ q=ggplot(data=data.frame(xx),aes(x=xx))+ geom_bar(aes(y = (..count..)),fill="orange")+ geom_text(aes(y = (..count..),label = ifelse((..count..)==0,"",scales::percent((..count..)/sum(..count..)))), stat="bin",colour="darkgreen") q } perbar(mtcars\$cyl)