rggplot2forecast

Replicating a Facet Chart from the Forecast Package as a ggplot2 Object


When I run this order using the forecast package, the following Facet Chart is currently produced.

library(fabletools)
library(forecast)

Test_plt<-fdeaths %>% 
  forecast()

checkresiduals(Test_plt)

enter image description here

Although Forecast works with ggplot2, what it produces cannot be called again as an object. For example, if I click on 'Test_plt', I will only see the test results conducted in the model but not the graph itself.

plot1<-checkresiduals(Test_plt)

 > plot1

    Ljung-Box test

data:  Residuals from ETS(M,N,M)
Q* = 11.592, df = 14, p-value = 0.639

Can anyone replicate this graph as a ggplot2 object so that it can be called later?


Solution

  • I don't see any easy option to return all plots and store them in a variable or as a list for further manipulation. But after a look at the source code of ggtsdisplay which is called under the hood by ckeckresiduals you can re-create the three subplots like so:

    library(fabletools)
    library(forecast)
    library(ggplot2)
    
    Test_plt <- fdeaths |>
      forecast()
    
    checkresiduals(Test_plt)
    
    tsplot <- autoplot(Test_plt$residuals) +
      geom_point(size = 0.5) +
      labs(y = NULL)
    
    acfplot <- ggAcf(Test_plt$residuals, lag.max = 24) +
      labs(title = NULL)
    
    histplot <- gghistogram(Test_plt$residuals, add.normal = TRUE, add.rug = TRUE) + 
      labs(x = "residuals")
    
    library(patchwork)
    
    tsplot / (acfplot + histplot)
    

    enter image description here