A Super Easy Way to Make Ggplot2 Bar Charts with Labels, ezplot - Part 4
In my very first tutorial on the ezplot R package, I showed you how easy and quick it is to make nice looking ggplot2 bar charts using ezplot. In this post, I’ll show you how to easily add labels on the bars. Let’s get started.
On Linux, install the R development package, usually called r-devel or r-base-dev.
Install devtools by running install.packages("devtools") in R.
Install and Load ezplot
We’ll use the diamonds data in the ggplot2 package. First, we count each clarity and calculate the percentages.
We want to make a bar chart displaying either the count or the percent of the clarities, and we want to label the bars with either the count or the percent. To do that, we first need to append columns of the label positions to the data frame tbl. We can easily do that using the add_bar_label_pos() function in ezplot. Run ?add_bar_label_pos in R to learn more about it, or add_bar_label_pos to see the function body.
Next, we make a function that can be used to draw bar charts based on variables in tbl_w_pos. If you’ve been reading the tutorials, this step should be familiar.
Now, we’re ready to draw bar charts. First, we draw a bar chart where y is freq and label the bars with freq, by default, it places the labels at the middle of the bars.
If you think it’s difficult to read the labels, you can easily place them at the top of the bars by passing in the argument barlab_at_top=T.
Another cool thing you can do is to label the bars with percent although the y-axis is frequency count. This is super easy too!
Finally, you can draw a bar chart where y is percent and label the bars with percent.
I created ezplot out of the frustration that there are too many detailed commands to remember when customizing a ggplot. If ezplot has improved your productivity, please share it with your friends, and you’re always welcome to drop a comment below. In addition, I’m writing a book called ezplot: How to Easily Make ggplot2 Graphics for Data Analysis, and it is 20% complete. Take a sneak peek and get notified when the book is published.