I have a lm of the form lm(log(z) ~ x*y)
.
I can make a 3D scatterplot of the data using s3d <- scatterplot3d(x,y,log(z))
.
How do I plot the surface of my regression function?
I know I can do s3d$plane3d(lm(log(z) ~ x + y)
for a simple linear model, but this doesn't work for nonplanar surfaces; e.g. s3d$plane3d(lm(log(z) ~ x * y)
won't work.
So first, you are much more likely to get help if you provide a sample dataset (or your actual data, which would be better) and a reproducible example of your code. Otherwise you are forcing us to do it - which I think is why your question was ignored for 6 hours. See this link for more details.
Second, using
lm(...)
like that, withformula=log(z)~x*y
is an exceptionally bad idea. Linear modeling is based on the assumption that the errors in the response (log(z)
in your case) are normally distributed with constant variance. If yourz-data
has normally distributed error with constant variance, thenlog(z)
certainly will not. This is a classic mistake; the right way to do this is using generalized linear modeling (see theglm
package, among others), withfamily=poisson
.Finally, to your question. The code below creates a 3D scatter plot overlaid onto a response surface. It uses the
rgl
package, which generates rotatable 3D plots.Here I've colored the points so that those below the surface are red and those above are green, and added dropline from each point to the surface.
The tricky bit is that in
surface3d(...)
, the x and y arguments are vectors corresponding to a grid, and z is a matrix with one row for every x value and one column for every y value.For your real data you may need to tweak the
scale=...
argument inopen3d(...)
.