简体   繁体   中英

How to plot a regression plane with an interaction in rgl

I want to plot the regression surface from a model with an interaction term using rgl 's interactive plotting system. It is easy to plot a regression plane for a model without an interaction term using:

plot3d(x=x1, y=x2, z=y1, type="s", col="yellow", size=1)
planes3d(a=coef(mod1)[2], b=coef(mod1)[3], c=-1, d=coef(mod1)[1], alpha=.5)

However, when the plane twists, this seems to be more difficult. Following on this question: 3D equivalent of the curve function in r , I am trying:

f2 <- function(x, y) as.vector(coef(mod2)%*%c(1, x, y, x*y))

curve_3d <- function(f2, x_range=c(0, 40), y_range=c(0, 40)){ 
  if (!require(rgl) ) {stop("load rgl")}

  xvec <- seq(x_range[1], x_range[2], by=1)
  yvec <- seq(y_range[1], y_range[2], by=1)
  fz   <- outer(xvec, yvec, FUN=f2)
  persp3d(xvec, yvec, fz, alpha=.5)
}
open3d()
plot3d(x=x1, y=x2, z=y2, type="s", col="yellow", size=1)
curve_3d(f2)

But, it's not working. (I've tried some other things as well, but I'm keeping this short.) My main problem so far seems to be with f2 ; however, I will also want this to look like planes3d , and I'm not sure if this is going to give me a wireframe.

Here's an example:

set.seed(897)
x1 = rep(c(0, 10, 20, 30, 40), times=25)
x2 = rep(c(0, 10, 20, 30, 40), each=25)
y2 = 37 + 0.7*x1 + 1.2*x2 - 0.05*x1*x2 + rnorm(125, mean=0, sd=5)
mod2 = lm(y2~x1*x2)
open3d()
plot3d(x=x1, y=x2, z=y2, type="s", col="yellow", size=1)
curve_3d(f2)
grd <- expand.grid(x1=unique(x1), x2=unique(x2) )
grd$pred <-predict(mod2, newdata=grd)
persp3d(x=unique(grd[[1]]), y=unique(grd[[2]]), 
              z=matrix(grd[[3]],5,5), add=TRUE)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM