Plotting each variable in a time series on the same plot

Viewed 46

I'm working through the book Forecasting Principles and Practice by Rob J Hyndman and George Athanasopoulos. The book can be found here: https://otexts.com/fpp3/

The book is generally very good, but I'm stuck on a point in chapter 7, Multiple Linear Regression.

Figure 7.4 shows, "Quarterly percentage changes in industrial production and personal savings and quarterly changes in the unemployment rate for the US over the period 1970Q1-2019Q2." As a business professional, I see this is the most valuable plot in the whole book, but there is no code how to reproduce it. The advantage of this plot is it shows each of the factors as a separate plot, grouped by quarter, so it's very easy to understand the effects of each factor on the result.

The plot can be found on this page: https://otexts.com/fpp3/regression-intro.html

This R code works, but is not really close to reproducing the figure in the book, the book does not provide the code to generate the plot, and the figure in the book is vastly better to use when explaining time series predictions to customers and managers than this code:

library(tidyverse)

library(fpp3)

us_change %>%
  autoplot(vars(Consumption, Income, Production, Savings, Unemployment))

Quarterly percentage changes in industrial production and personal savings and quarterly changes in the unemployment rate for the US over the period 1970Q1-2019Q2.

I have tried many variations of autoplot, gg_subseries, gg_tsdisplay, etc., but nothing is even close to the plot in the book. Any help would be warmly appreciated!

1 Answers

ggplot2 generally works most fluidly with "long" data, which can be created using tidyr::pivot_longer to put the values for each series in a common column, with another column ("name" here) distinguishing among the columns.

library(tidyverse)
us_change %>%
  pivot_longer(-Quarter) %>%
  ggplot(aes(Quarter, value, color = name)) +
  geom_line() +
  facet_wrap(~name, ncol = 1, scales = "free_y") +
  guides(color = "none")
  

enter image description here

Related