如何在 rgl 中绘制具有交互作用的回归平面 [英] How to plot a regression plane with an interaction in rgl
问题描述
我想使用 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)
然而,当飞机扭曲时,这似乎更困难.关于这个问题:r 中曲线函数的 3D 等效,我正在尝试:
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)
但是,它不起作用.(我也尝试过其他一些东西,但我保持简短.)到目前为止,我的主要问题似乎是 f2
;但是,我也希望它看起来像 planes3d
,我不确定这是否会给我一个线框.
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.
举个例子:
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)
这篇关于如何在 rgl 中绘制具有交互作用的回归平面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!