Time Series Plots Using ggplot2

Of course, the ggplot2 can also visualize time series. This section introduces the relevant ggplot2 syntax.

ggplot2 extensions for ts objects

The ggfortify package is an extension to ggplot2 that makes it easy to plot time series objects (Horikoshi and Tang 2017). It can handle the output of many time series packages, including: zoo::zooreg(), xts::xts(), timeSeries::timSeries(), tseries::irts(), forecast::forecast(), vars:vars().

Another interesting package is the ggpmisc package (Aphalo 2017), which provides two useful methods for time series object:

  • stat_peaks() finds at which x positions local y maxima are located, and
  • stat_valleys() finds at which x positions local y minima are located.

Here, we'll show how to easily:

  • Visualize a time series object, using the data set AirPassengers (monthly airline passenger numbers 1949-1960).
  • Identify shifts in mean and/or variance in a time series using the changepoint package.
  • Detect jumps in a data using the strucchange package and the data set Nile (Measurements of the annual flow of the river Nile at Aswan).
  • Detect peaks and valleys using the ggpmisc package and the data set lynx (Annual Canadian Lynx trappings 1821–1934).

First, install required R packages:

install.packages(
  c("ggfortify", "changepoint",
    "strucchange", "ggpmisc")
)

Then use the autoplot.ts() function to visualize time series objects, as follow:

library(ggfortify)
library(magrittr) # for piping %>%
# Plot ts objects
autoplot(AirPassengers)
# Identify change points in mean and variance
AirPassengers %>%
  changepoint:: cpt.meanvar() %>%  # Identify change points
  autoplot()
# Detect jump in a data
strucchange::breakpoints(Nile ~ 1) %>%
  autoplot()

 

Detect peaks and valleys:

library(ggpmisc)
ggplot(lynx, as.numeric = FALSE) + geom_line() + 
  stat_peaks(colour = "red") +
  stat_peaks(geom = "text", colour = "red", 
             vjust = -0.5, x.label.fmt = "%Y") +
  stat_valleys(colour = "blue") +
  stat_valleys(geom = "text", colour = "blue", angle = 45,
               vjust = 1.5, hjust = 1,  x.label.fmt = "%Y")+
  ylim(-500, 7300)