Practical Time Series Forecasting - Chapter 2

Author

Dave Hurst

library(tidyverse)
library(readxl)
library(lubridate)

Visualizing Time Series with ts and base R graphics

Amtrak Fig 2-2.R

Amtrak.data <- read.csv("../data/Amtrak data.csv")
ridership.ts <- ts(Amtrak.data$Ridership, start = c(1991,1), end = c(2004, 3), freq = 12)

# Figure 2-2
plot(ridership.ts, xlab = "Time", ylab = "Ridership", ylim = c(1300, 2300), bty = "l")

Amtrak Fig 2-4.R

library(forecast)

# Amtrak.data <- read.csv("Amtrak data.csv")
# ridership.ts <- ts(Amtrak.data$Ridership, start = c(1991,1), end = c(2004, 3), freq = 12)
ridership.lm <- tslm(ridership.ts ~ trend + I(trend^2))

# Figure 2-4
par(mfrow = c(2, 1))
plot(ridership.ts, xlab = "Time", ylab = "Ridership", ylim = c(1300, 2300), bty = "l")
lines(ridership.lm$fitted, lwd = 2)
ridership.ts.zoom <- window(ridership.ts, start = c(1997, 1), end = c(2000, 12))
plot(ridership.ts.zoom, xlab = "Time", ylab = "Ridership", ylim = c(1300, 2300), bty = "l")

Visualizing Time Series the tidyverse

Amtrak_data <- read_excel("../data/Amtrak data.xls", 
    col_types = c("date", "numeric"))

Amtrak_data %>% 
  mutate(fitted = ridership.lm$fitted) %>% 
  ggplot(aes(Month, Ridership)) +
  geom_line(alpha = 0.5) +
  geom_line(aes(y = fitted))

Amtrak_data %>% 
  mutate(fitted = ridership.lm$fitted) %>% 
  filter(year(Month) >= 1997,
         year(Month) <= 2000) %>% 
  ggplot(aes(Month, Ridership)) +
  geom_line(alpha = 0.5) +
  geom_line(aes(y = fitted))

Interactive Visualization with Plotly

Baregg Tunnel Traffic

library(plotly)

TunnelTraffic <- read_excel("TunnelTraffic.xls",
                            col_types = c("date", "numeric"))
tt_raw_plt <- TunnelTraffic %>% 
  ggplot(aes(Day, `# Vehicles in tunnel`)) +
  geom_line(color = 'dark blue') +
  theme_light()
ggplotly(tt_raw_plt)
tt_yearly_avg <- TunnelTraffic %>% 
  mutate(year = year(Day),
         month = month(Day)) %>% 
  group_by(year, month) %>% 
  summarise(`Vehicle Traffic` = mean(`# Vehicles in tunnel`),
            .groups = 'drop') %>% 
  mutate(Month = factor(month, labels = month.name ))

tt_year_plt <- tt_yearly_avg %>% 
  ggplot(aes(Month, `Vehicle Traffic`, group = 1)) +
  geom_line() +
  geom_smooth(span = 12) +
  ylim(0, NA) +
  facet_wrap(~ year, scales = "free_x") +
  theme(axis.text.x = element_text(angle = 45))

ggplotly(tt_year_plt)
tt_wday_plt <- TunnelTraffic %>% 
  mutate(`Day of Week` = weekdays(Day)) %>% 
  ggplot(aes(Day, `# Vehicles in tunnel`, color = `Day of Week`)) +
  geom_line() +
  ylim(0,NA) +
  theme_light()

ggplotly(tt_wday_plt)

Plotly enables interactive filtering. Double click on Day of Week element in the legend to isolate a single day, subsequent clicks add additional days back to the displayed data.

Example Plotly Image filtered by Day of Week