An Easy Way to Make Ggplot2 Plots, ezplot - Part 1

Master R

By Guangming Lang Comment

Do you love ggplot2 plots? If you’ve worked with ggplot2 before, you know that to get a satisfying plot, you often need to use many detailed ggplot2 syntaxes, which are difficult to remember and time consuming to look up. Wouldn’t it be awesome if there’re simpler and intuitive syntaxes? The answer is yes and the package ezplot does exactly that. In this and the next few posts, I’ll demo how to use ezplot.

Prerequisites

  1. Install a set of development tools
    • On Windows, download and install Rtools.
    • On Mac, install the Xcode command line tools.
    • On Linux, install the R development package, usually called r-devel or r-base-dev.
  2. Install devtools by running install.packages("devtools") in R.

Install and Load ezplot

devtools::install_github("gmlang/ezplot")
library(ezplot)

Make some fake data

# make some data
df = read.table(header=TRUE, text='
student grade
Joe 90
Mary 75
Alex 50')
df$pct = df$grade / sum(df$grade)
print(df)
##   student grade       pct
## 1     Joe    90 0.4186047
## 2    Mary    75 0.3488372
## 3    Alex    50 0.2325581

Create simple barplots

barplt = mk_barplot(df)
barplt("student", "grade", "student") 

center

barplt("student", "grade", "student", legend=F) 

center

p = barplt("student", "pct", "student", legend=F) 
scale_axis(p, scale="pct")

center

scale_axis(p, scale="pct", pct_jump=0.3, pct_max=0.6)

center

Make some fake data again

df2 = read.table(header=TRUE, text='
group level val
A      small 1.8
A      medium 2.2
A      large 1.5
B      small 2.0
B      medium 2.6
B      large 1.0
C      small 2.5
C      medium 1.3
C      large 2.9')

# Calculate the percentage of the levels within each group
library(tidyr)
library(dplyr)

pct = df2 %>% spread(level, val)
temp = pct[, 2:4]
pct = cbind(group=pct[, 1], temp / apply(temp, 1, sum))
pct = pct %>% gather(level, pct, -group)
pct$level = factor(pct$level, levels=c("small", "medium", "large"))

Make stacked barplots

# display counts
barplt = mk_barplot(df2)
barplt("group", "val", "level") 

center

# display percentages
barplt = mk_barplot(pct)
p = barplt("group", "pct", "level")
p = scale_axis(p, scale="pct")
print(p)

center

# use color-blind friendly palettes
cbPalette = cb_color("cb_gray")
p + ggplot2::scale_fill_manual(values=cbPalette)

center

# use customized palettes
red = cb_color("vermilion")
purple = cb_color("reddish_purple")
green = cb_color("bluish_green")
p + ggplot2::scale_fill_manual(values=c(red, purple, green))

center

I’m the creator of ezplot, if you have any questions, just 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.

If you enjoyed this post, get updates. It's FREE