Simple 3D plots in R

plot3d.png

References

Configure knitr

## For rgl package
knit_hooks$set(rgl = hook_rgl, webgl = hook_webgl)

Prepare data

## Load data
dat <- read.table(header = TRUE, text = "
y   x1  x2
12.37   2.23    9.66
12.66   2.57    8.94
12  3.87    4.4
11.93   3.1 6.64
11.06   3.39    4.91
13.03   2.83    8.52
13.13   3.02    8.04
11.44   2.14    9.05
12.86   3.04    7.71
10.84   3.26    5.11
11.2    3.39    5.05
11.56   2.35    8.51
10.83   2.76    6.59
12.63   3.9 4.9
12.46   3.16    6.96
")

## Check range
sapply(dat, range)
         y   x1   x2
[1,] 10.83 2.14 4.40
[2,] 13.13 3.90 9.66

Simple 3D scatter plot with scatter3d package

## Load scatterplot3d
library(scatterplot3d)

## Simple scatter plot
with(data = dat,
     scatterplot3d(x = x1,
                   y = x2,
                   z = y,
                   )
     )

plot of chunk unnamed-chunk-4


## Fit a linear regression
lmFit <- lm(y ~ x1 + x2, data = dat)


## Create x1, x2 values to predict y for
x1 <- seq(from = 2, to =  4, by = 0.1)
x2 <- seq(from = 4, to = 10, by = 0.1)

## Predict y
y <- outer(X = x1, Y = x2, FUN = function(x1, x2) {

    predict(lmFit, newdata = data.frame(x1 = x1, x2 = x2))
})

## Regression plane
persp(x = x1,
      y = x2,
      z = y,
      theta = 30, phi = 20, expand = 0.6, shade = 0.3)

plot of chunk unnamed-chunk-4

Interactive 3D graphics using rgl package

## knitr chunk option {r, rgl = TRUE, webgl = TRUE}
## rgl for static picture, webgl for dynamic

## Load rgl for 3d
library(rgl)

## Create x1, x2 values to predict y for
x1 <- seq(from = 2, to =  4, by = 0.05)
x2 <- seq(from = 4, to = 10, by = 0.05)

## Predict y
y <- outer(X = x1, Y = x2, FUN = function(x1, x2) {

    predict(lmFit, newdata = data.frame(x1 = x1, x2 = x2))
})

## Drop outlying y
y[y < min(dat$y) | y > max(dat$y)] <- NA

## Scatter plot
with(data = dat,
     plot3d(x = x1,
            y = x2,
            z = y,
            type = "s",  # s_phere
            col = "red",
            size = 2            
            )
     )

## Add regression surface
surface3d(x = x1,
          y = x2,
          z = y,
          col = 3, alpha = 0.5)

## Change perspective
rgl.viewpoint(theta = 0, phi = -90, fov = 60, zoom = 1)

## To write to dynamic html file
## writeWebGL(width = 500, height = 500)

unnamed_chunk_5snapshot
You must enable Javascript to view this page properly.

plot of chunk unnamed-chunk-5