Search code examples
rplottime-seriesautoplot

Why is the autoplot function giving an error in this example from publication "Forecasting: Principles and Practice" not working?


I am working through section 2.2 "Time Plots" of publication Forecasting: Principles and Practice by Hyndman and Athanasopoulos (https://otexts.com/fpp3/time-plots.html) and I can't get the autoplot() function referenced therein to work. I assume autoplot() derives from the forecast package but as you can see in the below code I have also fiddled with ggplot2 and ggfortify packages and neither of these work either. The error I get when trying the forecast package is "Error in forecast::autoplot():! Objects of class <tbl_ts> are not supported by autoplot."

Any ideas how to get this autoplot() function working?

Here's the publication's autoplot() output that I'm trying to ape:

enter image description here

Code (in this example I was trying forecast package by using forecast::autoplot(...); further note that installing the tsibbledata package provides the "ansett" data used in this example):

library(dplyr)
library(tsibble)
library(tsibbledata)
library(forecast)
library(ggplot2)
library(ggfortify)

melsyd_economy <- ansett %>%
  filter(Airports == "MEL-SYD", Class == "Economy") %>%
  mutate(Passengers = Passengers/1000)

forecast::autoplot(melsyd_economy, Passengers) +
  labs(title = "Ansett airlines economy class",
       subtitle = "Melbourne-Sydney",
       y = "Passengers ('000)")

Solution

  • The autoplot method for tsibbles is from the fabletools package. See Plot time series from a tsibble.

    library(dplyr)
    library(ggplot2)
    library(tsibbledata)
    library(fabletools)
    
    melsyd_economy <- ansett %>%
      filter(Airports == "MEL-SYD", Class == "Economy") %>%
      mutate(Passengers = Passengers / 1000)
    
    autoplot(melsyd_economy, Passengers) +
      labs(
        title = "Ansett airlines economy class",
        subtitle = "Melbourne-Sydney",
        y = "Passengers ('000)"
      )