I am trying to plot a 3Dplot of a linear regression with two variables.
My linear model:
ls = lm(mpg ~ disp + qsec, data = mtcars)
The minimum and maximum values to predict:
mmd = min(mtcars$disp):max(mtcars$disp)
mmq = min(mtcars$qsec):max(mtcars$qsec)
The linear function:
flm = function(x1, x2) ( (ls$coefficients[1]) + (ls$coefficients[2] * x1) + (ls$coefficients[3] * x2))
The outer matrix:
t = outer(X = mmd, Y = mmq, FUN = flm)
The plot:
persp3D(z = t, ticktype = "detailed")
Now I would like to control for the non-linearity of the qsec
parameter.
Is this the right way to do it?
ls = lm(mpg ~ disp + poly(qsec, degree = 2), data = mtcars)
mmd = min(mtcars$disp):max(mtcars$disp)
mmq = min(mtcars$qsec):max(mtcars$qsec)
flm = function(x1, x2) ( (ls$coefficients[1]) + (ls$coefficients[2] * x1) +
(ls$coefficients[3] * x2)
+ (ls$coefficients[4] * x2)
)
t = outer(X = mmd, Y = mmq, FUN = flm)
persp3D(z = t, ticktype = "detailed")