Search notes:

R package: rgl

rgl allows to use OpenGL functions from R, for example to produce rotable 3d plots.

Creating a surface from a function

The following example creates a surface from a function:
library(rgl);

open3d(windowRect=c(34, 57, 727, 707));

plot3d(
 # ----------------------------------------
   function(x, y) {
     ( ((x+1.1*y)^2) + (3*(y+0.09)^2) ) * exp(-(x^2)-(y^2 ))
   },
 # ----------------------------------------
   col    = colorRampPalette(c('#4499ff', '#ee9933')),
   xlab   = 'x',
   ylab   = 'y',
   zlab   = 'f(x,y)',
   xlim   = c(-3, 3),
   ylim   = c(-3, 3),
   aspect = c(1, 1, 0.5)
);

#
# After rotating the plot with the mouse,
# the matrix data can be determined with:
#
#   par3d()$userMatrix
#
view3d(
  userMatrix = matrix(
     c(
        0.8091025 ,  0.5799688 , -0.09481177 , 0,
       -0.1589791 ,  0.3713353 ,  0.91478717 , 0,
        0.5657551 , -0.7250838 ,  0.39265123 , 0,
        0.0000000 ,  0.0000000 ,  0.00000000 , 1
      ),
      nrow = 4,
      byrow = TRUE
    )
);
Github repository about-r, path: /packages/rgl/surface-function.R

TODO

Simple example

library(rgl)

open3d()

x <- sort(rnorm(1000))
y <-      rnorm(1000)
z <-      rnorm(1000) + atan2(x,y)

plot3d(x, y, z, col=rainbow(1000))
Github repository about-r, path: /packages/rgl/example-1.R

Creating an animation

library(rgl)

open3d()
plot3d(cube3d(col="green"));

M <- par3d("userMatrix")

play3d(
  par3dinterp(
     userMatrix=list(M, rotate3d(M, pi/2, 1, 0, 0),
                        rotate3d(M, pi/2, 0, 1, 0) )
  ),
  duration=4
);
Github repository about-r, path: /packages/rgl/play3d.R

Same thing, but creating a movie

library(rgl)

open3d();
plot3d(cube3d(col="green"));

M <- par3d("userMatrix")

movie3d(
  par3dinterp(
     userMatrix=list(M, rotate3d(M, pi/2, 1, 0, 0),
                        rotate3d(M, pi/2, 0, 1, 0) )
  ),
  dir     = '.',
  clean   = FALSE,
  duration= 4
);
Github repository about-r, path: /packages/rgl/movie3d.R
The movie is stored as a *.gif.

Plotting some does

library(rgl)

open3d()

a  <- seq(0, 4*pi, length=100)

x <- sin(a)
y <- cos(a)
z <- a / max(a)

plot3d(x, y, z)
Github repository about-r, path: /packages/rgl/plot3d.R

See also

The scatter3d function in the package car.
With the tests outlined in coordinates and axes, I tried to get more clarity about rgl's coordinate system and how axes are plotted.
R functions for graphics
R packages

Index