Scatter3D 添加多个曲面

Scatter3D add multiple surfaces

我正在尝试将多个表面添加到 R 中的一个 scatter3d 图。这是 scatter3d 文档中的示例:

library(plot3D)

with (mtcars, {
  
  # linear regression
  fit <- lm(mpg ~ wt + disp)
  
  # predict values on regular xy grid
  wt.pred <- seq(1.5, 5.5, length.out = 30)
  disp.pred <- seq(71, 472, length.out = 30)
  xy <- expand.grid(wt = wt.pred, 
                    disp = disp.pred)
  
  mpg.pred <- matrix (nrow = 30, ncol = 30, 
                      data = predict(fit, newdata = data.frame(xy), 
                                     interval = "prediction")[,1])
  
  # fitted points for droplines to surface
  fitpoints <- predict(fit) 
  
  scatter3D(z = mpg, x = wt, y = disp, pch = 18, cex = 2, 
            theta = 20, phi = 20, ticktype = "detailed",
            xlab = "wt", ylab = "disp", zlab = "mpg",  
            surf = list(x = wt.pred, y = disp.pred, z = mpg.pred,  
                        facets = NA, fit = fitpoints),
            main = "mtcars")
  
})

产生以下情节:

假设我想再添加两个表面:

surf1<-mpg.pred+5
surf2<-mpg.pred-5

我该怎么做?

您可以使用 surf3Dadd = TRUE 来添加额外的表面:

library(plot3D)

with (mtcars, {
  
  # linear regression
  fit <- lm(mpg ~ wt + disp)
  
  # predict values on regular xy grid
  wt.pred <- seq(1.5, 5.5, length.out = 30)
  disp.pred <- seq(71, 472, length.out = 30)
  xy <- expand.grid(wt = wt.pred, 
                    disp = disp.pred)
  
  mpg.pred <- matrix (nrow = 30, ncol = 30, 
                      data = predict(fit, newdata = data.frame(xy), 
                                     interval = "prediction")[,1])
  
  # fitted points for droplines to surface
  fitpoints <- predict(fit) 
  
  p1 <- scatter3D(z = mpg, x = wt, y = disp, pch = 18, cex = 2,
               theta = 20, phi = 20, ticktype = "detailed",
               xlab = "wt", ylab = "disp", zlab = "mpg",
               surf = list(x = wt.pred, y = disp.pred, z = mpg.pred,
                           facets = NA, fit = fitpoints),
               main = "mtcars")
  p2 <- surf3D(x = matrix(wt.pred, 30,30),
            y = matrix(disp.pred, 30,30,byrow=TRUE), z = mpg.pred + 5, facets = NA, add = TRUE)
  p3 <- surf3D(x = matrix(wt.pred, 30,30),
            y = matrix(disp.pred, 30,30,byrow=TRUE), z = mpg.pred - 5, facets = NA, add = TRUE)
})

reprex package (v2.0.1)

创建于 2022-04-27

图例和配色方案有点错误;你也许可以修复它们,但我不知道如何。在两个 surf3D 调用中使用 colkey=list(plot=FALSE) 有点帮助,但额外平面的配色方案仍然是错误的。