Search code examples
rplotforecast

How I can avoid the hole in the plot forecast with series plot R


I write this question because I can't link (I tried for many times), in the plot, the series with the forcast.

Here the code that I used.

AA1<-AA_1
str(AA1)#OUTPUT: Time-Series [1:60] from 2013 to 2018: 309 368 1602 6742 19396


Serie1<-Serie_1
str(Serie1) ##OUTPUT:Classes ‘tbl_df’, ‘tbl’ and 'data.frame':  60 obs. of  7 variables:


X_Reg_Mod_Completo <- cbind(A=ts(Serie1$A),B=ts(Serie1$B), 
                     C=ts(Serie1$C), D=ts(Serie1$D),
                     E=ts(Google1$E), F=ts(Serie1$F))

Mod_Completo<-auto.arima(AA1, xreg=X_Reg_Mod_Completo, trace = TRUE, test = "kpss", ic="aic", seasonal = TRUE)
AIC(Mod_Completo)
FOR_Mod_Completo<-forecast(Mod_Completo,xreg=X_Reg_Mod_Completo)
plot(FOR_Mod_Completo,xlim=c(2016, 2019))

My goal is to avoid the hole between the end of 2018 and gennary 2018.

If somebody need the data, please, write a comment and I will update.

Thank you in advance for your help.

Francesco


Solution

  • I've tried something with ggplot2 without messing up too much with the forecast, maybe it could help as a start:

    library(forecast)
    library(tidyverse)
    fit <- auto.arima(WWWusage)
    forec <- forecast(fit,h = 10)
    

    Now, we have to put the ts and the forecast in data.frames, bind them, and plot the result with ggplot2:

    # time series
    ts_ <- data.frame(Point.Forecast = WWWusage,
                      Lo.80=NA,
                      Hi.80=NA,
                      Lo.95=NA,
                      Hi.95=NA,
                      type = 'ts')
    
    # forecasting
    forec <- data.frame(forec, type ='fc')
    
    # together
    tot <- union_all(ts_,forec) 
    
    # now add the date, in this case I put a sequence: len
    tot$time <- seq( as.Date("2011-07-01"), by=1, len=nrow(ts_)+nrow(forec))
    

    Now you can plot it:

      ggplot(tot) + geom_line(aes(time,Point.Forecast))+
                    geom_line(aes(time, Lo.95))+
                    geom_line(aes(time, Hi.95))+
                    geom_line(aes(time, Lo.80))+
                    geom_line(aes(time, Hi.80))+
                    geom_vline(xintercept=tot$time[nrow(ts_)], color = 'red') + theme_light()
    

    enter image description here