Bar charts with percentage labels but counts on the y axis

[This article was first published on socialdatablog » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
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)

Rplot04

To leave a comment for the author, please follow the link and comment on their blog: socialdatablog » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)