如何使用rgl中的交互绘制回归平面

时间:2013-02-18 02:42:50

标签: r plot regression interaction rgl

我想使用rgl的交互式绘图系统从具有交互项的模型绘制回归曲面。使用以下方法很容易为没有交互项的模型绘制回归平面:

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)

然而,当飞机扭曲时,这似乎更难。关于这个问题:3D equivalent of the curve function in r,我正在尝试:

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)

但是,它不起作用。 (我也尝试过其他一些东西,但我保持这么简短。)到目前为止我的主要问题似乎是f2;但是,我也希望这看起来像planes3d,我不确定这是否会给我一个线框。

以下是一个例子:

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)

1 个答案:

答案 0 :(得分:4)

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)

enter image description here

相关问题