0

I am working with multiple linear regression.

I have z output which is a result of a x*y interaction.

I would like to create a surface plot of these data, but haven't had any luck. I have tried the commandoes wireframe and persp, but it seems like I'm not able to design my commandoes yet.

I have created a beautiful scatterplot3d, but how can I create a surface plot of the same data?

Octahedron
  • 893
  • 2
  • 16
  • 31
  • Welcom to SO. Even if you get an answer, please read this: [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – agstudy Jul 04 '13 at 14:53
  • possible duplicate of [Plot Regression Surface](http://stackoverflow.com/questions/7863906/plot-regression-surface) and also search SO for `scatter3d` which offers possibility of rgl graphics with point and surface, rather than the static versions provided by `scatterplot3d` – IRTFM Jul 04 '13 at 16:58

2 Answers2

4

I assume you know what you're doing when you say you've fitted a 3D surface in a linear regression. What persp and wireframe expect is a grid of x and y values, along with the predicted z-heights at each of those grid points. You can generate this using expand.grid. Here's an indicative example.

preddf <- expand.grid(x=seq(xmin, xmax, len=51),
                      y=seq(ymin, ymax, len=51))

preddf$z <- predict(model, preddf)

persp(preddf)

Replace xmin, xmax, ymin and ymax with the ranges of your predictors, and 51 with the desired size/density of your grid.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
3

Another alternative to expand.grid is to use outer,it is faster.

Using @HongOoi data:

z <- outer(x,y, function(x,y) 
  predict(mod,data.frame(x=x,y=y)))
persp(x,y,z)
Thomas
  • 43,637
  • 12
  • 109
  • 140
agstudy
  • 119,832
  • 17
  • 199
  • 261