Search code examples
rlinear-regressiontimeserieschart

replicate multiple regression plot from excel in R


I am struggling with reproducing a multiple linear regression plot in R which is rather easily obtainable in Excel. I make an example. Say I have the following data frame (called test) in R:

y   x1  x2  x3
2   5   5   9
6   4   2   9
4   2   6   15
7   5   10  6
7   5   10  6
5   4   3   12

To generate a linear regression, I simply write:

reg=lm(y ~ x1 + x2 + x3, data = test)

Now I would like to create a plot of the actual value of the y variable, the predicted y and on a secondary axis the standardised residuals. I add a screenshot from Excel so you see what I mean.

To access the Excel plot I would like to obtain: the plot is in italian, "y" means observed y values, "Y prevista" means predicted Y values and "Residui standard" means standardized residuals. The standard residuals are plotted on a secondary axis

If anyone could show me who I can achieve the above in R, it would be very appreciated.


Solution

  • Use something like

    matplot(seq(nrow(test)), cbind(test$y, predict(reg), rstudent(reg)), type="l")
    

    but you'd have to set the axes to make sure everything is okay