1

Using car::scatter3d(), I am trying to create a 3D figure with a regression surface indicating an interaction between a categorical and a continuous variable. Partly following the code here, I obtained a figure below.

enter image description here

The figure is obviously wrong in that the regression surface does not reach one of the values of the categorical variable. The problem perhaps lies in the use of the rgl::persp3d() (the last block of the code below), but I have not been able to identify what exactly I'm doing wrongly. Could someone let me know what I'm missing and how to fix the problem?

library(rgl)
library(car)
n <- 100
set.seed(1)
x <- runif(n, 0, 10)
set.seed(1)
z <- sample(c(0, 1), n, replace = TRUE)
set.seed(1)
y <- 0.5 * x + 0.1 * z + 0.3 * x * z + rnorm(n, sd = 1.5)
d <- data.frame(x, z, y)
scatter3d(y ~ x + z, data = d, 
  xlab = "continuous", zlab = "categorical", ylab = "outcome",
  residuals = FALSE, surface = FALSE
)

d2 <- d
d2$x <- d$x / (max(d$x) - min(d$x))
d2$y <- d$y / (max(d$y) - min(d$y))
mod <- lm(y ~ x * z, data = d2)
grd <- expand.grid(x = unique(d2$x), z = unique(d2$z))
grd$pred <- predict(mod, newdata = grd)
grd <- grd[order(grd$z, grd$x), ]

# The problem is likely to lie somewhere below.
persp3d(x = unique(grd$x), y = unique(grd$z), 
  z = matrix(grd$pred, length(unique(grd$z)), length(unique(grd$x))), 
  alpha = 0.5,
  col = "blue",
  add = TRUE,
  xlab = "", ylab = "", zlab = ""
)

I prefer sticking to car::scatter3d() in drawing the original graph because I already made several figures with car::scatter3d() and want to make this figure consistent with them as well.

Community
  • 1
  • 1
Akira Murakami
  • 463
  • 1
  • 4
  • 14
  • If `z` is a factor then by definition it can only take on values `0` and `1`; values between 0 ad 1 are meaningless. So there is no 3D surface, there are two curves: y vs x when z=0 and y vs x when z=1. – jlhoward Nov 01 '14 at 21:54
  • I want to demonstrate that a factor as an independent variable is just a special case of regression modeling with continuous variables, and for this purpose, I thought it could help to have a figure like the above (because I'd put a similar figure with continuous variables). But you are right that most part of the surface is meaningless and having a surface drawn can be misleading... – Akira Murakami Nov 02 '14 at 19:05
  • Perhaps [this](https://stackoverflow.com/a/51861588/5784831) solves your problem? I guess only the formula for `z` will change... – Christoph Aug 15 '18 at 19:30

0 Answers0