wittyalias
wittyalias

Reputation: 45

Facet a fabletools autoplot of a fable forecast by model

Is there any way to use autoplot with a fable, but facet it by the model? The code below produces a nice little graph, but overlays the forecasts on top of each other.

library(tidyverse)
library(tsibble)
library(feasts)
library(fable)
library(fabletools)

tourism_melb <- tourism %>%
    filter(Region == "Melbourne") %>% 
    filter(Purpose == "Business") %>% 
    select(-Region, -State, -Purpose)

fableModels <- tourism_melb %>% 
    model(arima = ARIMA(), tslm = TSLM(Trips ~ trend()), mean = MEAN(window = 4))

forecasts <- fableModels %>% 
    forecast(h = "2 years")

forecasts %>% autoplot(tourism_melb)

It looks like this: forecasts stacked on top of each other

I'm looking for something more like this, except faceted, so that I don't have to muck about with axis scales and labels and the like:

library(gridExtra)

arimaPlot <- forecasts %>% 
    filter(.model == "arima") %>% 
    autoplot(tourism_melb)

tslmPlot <- forecasts %>% 
    filter(.model == "tslm") %>% 
    autoplot(tourism_melb)

grid.arrange(arimaPlot, tslmPlot)

enter image description here

It seems like something that would be pretty commonly done, but I know that autoplot for these is meant to be pretty quick and dirty, so I don't know if it has that functionality. I looked through the fabletools github, but wasn't able to to find anything.

Upvotes: 2

Views: 542

Answers (1)

stefan
stefan

Reputation: 124013

Maybe this is what you are looking for. As autoplot returns a ggplot object you could simply add facet_wrap(~.model, ncol = 1)

library(tidyverse)
library(tsibble)
library(feasts)
library(fable)
library(fabletools)

tourism_melb <- tourism %>%
  filter(Region == "Melbourne") %>% 
  filter(Purpose == "Business") %>% 
  select(-Region, -State, -Purpose)

fableModels <- tourism_melb %>% 
  model(arima = ARIMA(), tslm = TSLM(Trips ~ trend()), mean = MEAN(window = 4))

forecasts <- fableModels %>% 
  forecast(h = "2 years")

forecasts %>% autoplot(tourism_melb) + facet_wrap(~.model, ncol = 1)

Upvotes: 2

Related Questions