June 11, 2014

Bar charts with percentage labels but counts on the y axis

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!

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

ggplot R reproducibleResearch code

Previous post
GANTT software I quite often get asked (and ask myself) what is the best GANTT software for basic use. Recently we have been comparing a few solutions so here are
Next post
Measuring resilience This article is work in progress! Feel free to add a comment. There should be a pdf at this link. After the terrible earthquake in Haiti in 2010,

This blog by Steve Powell is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, syndicated on r-bloggers and powered by Blot.
Privacy Policy