Search code examples
rggplot2forecastautoplot

Removing gap between historical and forecasted in autoplot from forecast package


?autoplot.forecast
If showgap=FALSE, the gap between the historical observations and the forecasts is removed.

However, for me it is not removed.

library(forecast)

d <- ts(rnorm(36), start = c(2021, 1), frequency = 12)

fc <- snaive(d, h = 12)

autoplot(fc, showgap = FALSE)

Using plot works fine however

plot(fc, showgap = FALSE)

Solution

  • OP, I originally thought this was a bug in the forecast::autoplot() function, but it turns out it is not. The function plot.forecast(), which is run when you use plot() on a 'forecast' object, contains the showgap= argument. The command ?autoplot.forecast does indicate the showgap= argument, but not for autoplot() - it's for the plot.forecast() function.

    The good news is that there appears to be a method within autolayer(...) that contains this argument and you can use it. i.e. check the help again for plot.forecast() a bit lower and you'll see this:

    ## S3 method for class 'forecast'
    autolayer(object, series = NULL, PI = TRUE, showgap = TRUE, ...)
    

    We can use autolayer() in concert with autoplot(). So, this seems to work:

    autoplot(fc) + autolayer(fc, showgap = F)
    

    enter image description here