user2550781
user2550781

Reputation: 9

How do I create a 3D surface plot in R?

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?

Upvotes: 0

Views: 603

Answers (2)

agstudy
agstudy

Reputation: 121608

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)

Upvotes: 3

Hong Ooi
Hong Ooi

Reputation: 57696

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.

Upvotes: 4

Related Questions