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 this in our graphics package of choice, ggplot? ggplot makes histograms by doing a stat transformation, stat_bin. Sure, this is helpful because you don’t have to prepare your data so much first, it will work out the bins and bin size for you. But it makes it correspondingly harder to customise the plot to get what you want, - concretely, in this case, to get percentage labels.
This is the cleanest way I could find - if you have a better idea, please post a comment!
library(ggplot2)
library(scales)
perbar=function(xx,xlab=""){
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+ylab("Count")+xlab(xlab)
}
perbar(mtcars$cyl)