(This article was first published on

**socialdatablog » R**, and kindly contributed to R-bloggers)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)
```

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...