I want to plot residual vs fitted plot in R to show linearity of my data. I am using tslm() function. This is what I did.
> plot(ts_model)
Error in `[.default`(X, , piv, drop = FALSE) :
incorrect number of dimensions
I am unable to use plot() function. I tried another way to plot the residual vs fitted pot.
> #Get list of residuals
> res <- resid(ts_model)
>
> #Linearity
> plot(fitted(ts_model),res)
> abline(0,0)
However, the red line is not showing. I want to include the red line to show the linearity.
I want something like the above. This plot is using lm function but I want to plot this using tslm() fucntion.
According to the documentation of plot.lm()
, the red line of the plot.lm()
function is obtained when parameter add.smooth=TRUE
. In turn, this parameter uses panel.smooth()
to generate a smoothed curve that fits the plotted points. Finally, the documentation of panel.smooth()
tells us that the function responsible for doing the smooth fit is lowess()
.
Therefore, a line that plots the result of the call to lowess()
should suffice to generate the red line that you are after. The following code illustrates (showcased with the sample data given in help(tslm)
of the forecast
package):
# Make generated plot reproducible
set.seed(1313)
# Generate the sample data
y <- ts(rnorm(120,0,3) + 1:120 + 20*sin(2*pi*(1:120)/12), frequency=12)
# Fit the tslm model
fit <- tslm(y ~ trend + season)
# Plot the residuals vs. fitted graph
# (note the use of as.numeric(), o.w. the points are connected by lines)
plot(as.numeric(fitted(fit)), as.numeric(residuals(fit)), type="p")
# Add a smooth trend line calling lowess(), as used by the plot.lm() function
lines(lowess(fitted(fit), residuals(fit)), col="red")
This is the resulting plot: