13.9 Saving a Three-Dimensional Plot

13.9.1 Problem

You want to save a three-dimensional plot created with the rgl package.

13.9.2 Solution

To save a bitmap image of a plot created with rgl, use rgl.snapshot(). This will capture the exact image that is on the screen:

library(rgl)
plot3d(mtcars$wt, mtcars$disp, mtcars$mpg, type = "s", size = 0.75, lit = FALSE)

rgl.snapshot('3dplot.png', fmt = 'png')

You can also use rgl.postscript() to save a PostScript or PDF file:

rgl.postscript('3dplot.pdf', fmt = 'pdf')

rgl.postscript('3dplot.ps', fmt = 'ps')

PostScript and PDF output does not support many features of the OpenGL library on which rgl is based. For example, it does not support transparency, and the sizes of objects such as points and lines may not be the same as what appears on the screen.

13.9.3 Discussion

To make the output more repeatable, you can save your current viewpoint and restore it later:

# Save the current viewpoint
view <- par3d("userMatrix")

# Restore the saved viewpoint
par3d(userMatrix = view)

To save view in a script, you can use dput(), then copy and paste the output into your script:

dput(view)

Once you have the text representation of the userMatrix, add the following to your script:

view <- structure(c(0.907931625843048, 0.267511069774628, -0.322642296552658,
0, -0.410978674888611, 0.417272746562958, -0.810543060302734,
0, -0.0821993798017502, 0.868516683578491, 0.488796472549438,
0, 0, 0, 0, 1), .Dim = c(4L, 4L))

par3d(userMatrix = view)