R中scatter3D()中曲面图的GLM预测

时间:2016-06-22 19:36:23

标签: r predict scatter3d

我尝试使用scatter3D()函数生成一个覆盖二项GLM的点的曲面图。

为此,我使用predict()来预测不同x和y值的z表面。

# Data:

library(plot3D)

structure(list(
x = c(0.572082281112671, -0.295024245977402, 0.295024245977402, 0.861117839813232, 0.572082281112671, -1.74020183086395, 0.861117839813232, 0.283046782016754, 0.861117839813232, 0.283046782016754, -0.295024245977402, 1.43918883800507, 1.43918883800507, -0.295024245977402, -0.00598874036222696, -0.873095273971558, -0.295024245977402, -0.00598874036222696, -0.00598874036222696, 0.861117839813232), 
y = c(-1.09869265556335, -1.18406093120575, -0.0542464517056942, -0.192688703536987, -0.0208134315907955, 0.194501429796219, -0.126082852482796, 0.861439049243927, 0.624606966972351, -0.227061957120895, -1.32208430767059, -0.553429543972015, 0.538678884506226, 1.53797924518585, 0.230196505784988, 0.2959825694561, 0.158534705638885, 1.33240795135498, 0.0964559689164162, 0.740677952766418), 
z = c(0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 
w = structure(c(2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L), .Label = c("0", "1"), class = "factor")), .Names = c("x", "y", "z", "w"), row.names = c(NA, 20L), class = "data.frame")

模特等

fit <-glm(formula = z ~ x * y + w, family = binomial)

# x is continuous
# y is continuous
# w is dichotomous (yes, no, i.e. 0,1) [but see solution below]
# z is dichotomous, but kept as numeric for plotting

grid.lines = 100
x.pred <- seq(min(x), max(x), length.out = grid.lines)
y.pred <- seq(min(y), max(y), length.out = grid.lines)
xy <- expand.grid( x = x.pred, y = y.pred)

z.pred <- matrix(exp(predict(fit, newdata = xy)), 
             nrow = grid.lines, ncol = grid.lines)

# fitted points for droplines to surface
fitpoints <- exp(predict(fit))

但是,我收到此错误:

Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : variable lengths differ (found for 'w')

W是第三个变量,对于保留在模型中非常重要,但是我仍然无法在绘制其他变量的同时弄清楚如何使其保持不变。我知道我需要调整一些东西,但似乎无法弄明白究竟是什么。

请注意,我对值进行取幂,因此它们是一个有意义的比例,介于0和1之间,这是我绘制图形时的概率。如果这不正确,请告诉我。 [这是不正确的 - 在下面的评论中指出]

我说完了:

scatter3D(x, y, z, pch = 21,  type = "p",col=rgb(red=0, green=17, blue=255, maxColorValue = 255, alpha = 150), bg = "#FF0000",
      ylab = "Z-AM-Testosterone", xlab = "Z-AR-CAGn", zlab = "Divorce",
      theta = -70, phi = 20, ticktype = "detailed",
      surf = list(x = x.pred, y = y.pred, z = z.pred,
                  fit  = fitpoints))

我确定它很简单,但是如果有人可以解释如何从预测中删除w或保持不变,那么我可以继续前进,我非常感激。请不要建议另一种3D绘图方法 - 对于我的目的,scatter3D优于visreg或其他方法。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

感谢简单的解决方案@Ben Bolker。

我取了yes / no,0-1变量的数字等价物的平均值,只是绘制了预测:

xy <- expand.grid( x = x.pred, y = y.pred, w = mean(w))

这让我可以根据数据生成一个看起来很合理的图表,如下所示。

Scatter3D用于负二项式模型,具有第三个二分法协变量(w)的平均值,在将w转换为数字之后:

3D plot of interaction