How to easily make ggplot2 type of time series plot, ezplot - Part 6

Master R

By Guangming Lang Comment

Time series plot is commonly used and this post will show you how easy it is to make them using the mk_lineplot() function from the ezplot package.

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)

The ezplot package comes with a films dataset containing the annual boxoffice/budget ratio between 1913 and 2014. We can plot these ratios over the years.

plt = mk_lineplot(bo_bt_ratio_by_year)
title = "Boxoffice/Budget Ratio from 1913 to 2014"
p = plt("year", "bo_bt_ratio", ylab="boxoffice/budget ratio", main=title)
print(p)

center

It might be more informative if we use log10 scale on the y-axis.

scale_axis(p, scale = "log10")

center

We can also change the width of the line and the size of the points by passing values to the linew and pt_size arguments.

p = plt("year", "bo_bt_ratio", ylab="boxoffice/budget ratio", main=title,
        linew=1, pt_size=2)
print(p)

center

We can also use log scale on the y-axis.

scale_axis(p, scale = "log")

center

Finally, we can plot two time series and color them differently. For example, we can plot annual total budget and boxoffice over the years on the same plot.

plt = mk_lineplot(btbo_by_year)
title = "Annual Total Budget and Boxoffice from 1913 to 2014"
red = cb_color("reddish_purple")
green = cb_color("bluish_green")
plt("year", "tot", "type", ylab="total amount ($billion)", main=title) + 
        ggplot2::scale_color_manual(values=c(red, green))

center

I created ezplot because there are too many detailed commands to remember when customizing a ggplot. If ezplot has improved your productivity, please tell your friends about it. In addition, I’m writing a book called ezplot: How to Easily Make ggplot2 Graphics for Data Analysis, and it is 20% complete. Read the sample chapters for FREE and get notified when the book is published.

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