mtcars

## =======================================================================
## scatter3D with fitted surface : the mtcars dataset
## implemented by Karline Soetaert
## =======================================================================

require(plot3D)

attach(mtcars)

# linear fit
fit <- lm(mpg ~ wt+disp)

# predict on x-y grid, for surface
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"))

# predicted z-values, 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", clab = "mpg", 
      surf = list(x = wt.pred, y = disp.pred, z = mpg.pred, 
                  facets = NA, fit = fitpoints),
      colkey = list(length = 0.8, width = 0.4),            
      main = "mtcars")

detach(mtcars)

# TRY: 
# require(plot3Drgl)
# plotrlg()

Go back