Search code examples
rlinear-regressionforecasting

Forecast plot for regression models only available for a single predictor


Sample data:- 
df:- 

      d     a     b     c
1  -4.41  Area1   NA    5.7
2  -5.22  Area1   25   5.9
3  -5.80  Area1   35    5.9
4  -5.20  Area2   58    9
5  -3.59  Area2   59    9
6  -3.53  Area2   129   9

require(forecast)

m <- lm(d ~ a + b + c, data=df)
f <- forecast.lm(m,df)
plot.forecast(f)

I am doing an in sample test for my model. I get the forecasted values when I display the object 'f'but when I try to plot it, it gives me an error as noted in the subject line along with the following line.

Error in plotlmforecast(x, plot.conf = plot.conf, shaded = shaded, shadecols = shadecols,  : 
 Forecast plot for regression models only available for a single predictor    

I thought it might be because of NA values in the data, but it gives the same error even after removing those values. Can anyone help on this?


Solution

  • You can plot the two values against each other with ggplot2 after melting the data frame with both vectors:

    library(ggplot2)
    library(reshape2)
    set.seed(318)
    df <- as.data.frame(replicate(4, rnorm(100)))
    names(df) <- letters[1:4]
    m <- lm(d ~ a + b + c, data=df)
    f <- forecast.lm(m,df)
    
    newdf <- melt(data.frame(d=df$d, f=f$mean))
    newdf$ind <- rep(seq(length(df$d)), 2)
    
    ggplot(newdf, aes(x=ind, y=value, color=variable)) + geom_line()
    

    enter image description here