source("setup.R") knitr::opts_chunk$set(rgl.newwindow = TRUE) set.seed(123)
rgl package is used to produce interactive 3-D plots. It contains
high-level graphics commands modelled loosely after classic R graphics,
but working in three dimensions. It also contains low level structure
inspired by (but incompatible with) the
This document gives an overview. See the help pages for details.
About this document
This document was written in R Markdown, using the
for production. It corresponds to rgl version
Most of the highlighted function names are HTML links. The internal links should work in any browser; the links to help topics should work if you view the vignette from within the R help system.
Basics and High Level Functions
r indexfns("plot3d") function
plots points within an rgl window. It is similar to the classic
r linkfn("plot", pkg="graphics") function,
but works in 3 dimensions.
with(iris, plot3d(Sepal.Length, Sepal.Width, Petal.Length, type="s", col=as.numeric(Species))) rglwidget()
can be used to plot three columns of the
Allowed plot types include
"p", "l", "h", "s",
meaning points, lines, segments from z=0, and spheres. There's
a lot of flexibility in specifying the coordinates; the
r linkfn("xyz.coords", pkg = "grDevices") function
grDevices package is used for this.
You can use your mouse to manipulate the plot. The default is that if you click and hold with the left mouse button, you can rotate the plot by dragging it. The right mouse button is used to resize it, and the middle button changes the perspective in the point of view.
If you call
r linkfn("plot3d") again, it will overwrite the current plot.
To open a new graphics window, use
The other high level function is
r indexfns("persp3d") to draw surfaces.
similar to the classic
r linkfn("persp", pkg = "graphics")
function, but with greater flexibility.
First, any of
can be specified using matrices, not just
z. This allows parametric
surfaces to be plotted.
An even simpler specification is possible:
x may be a function,
in which case
persp3d will work out the grid itself. See
r linkfn("persp3d.function", text="?persp3d.function", pkg="rgl")
for details. For example, the
MASS package estimates
Gamma parameters using maximum likelihood in a
r linkfn("fitdistr", text="?MASS::fitdistr", pkg="MASS") example.
Here we show the log likelihood surface.
library(MASS) # from the fitdistr example set.seed(123) x <- rgamma(100, shape = 5, rate = 0.1) fit <- fitdistr(x, dgamma, list(shape = 1, rate = 0.1), lower = 0.001) loglik <- function(shape, rate) sum(dgamma(x, shape=shape, rate=rate, log=TRUE)) loglik <- Vectorize(loglik) xlim <- fit$estimate+4*fit$sd*c(-1,1) ylim <- fit$estimate+4*fit$sd*c(-1,1) mfrow3d(1, 2, sharedMouse = TRUE) persp3d(loglik, xlim = xlim, ylim = ylim, n = 30) zlim <- fit$loglik + c(-qchisq(0.99, 2)/2, 0) next3d() persp3d(loglik, xlim = xlim, ylim = ylim, zlim = zlim, n = 30)
On the left, the whole surface over a range of the parameters; on the right, only the parts of the surface with log likelihood values near the maximum.
Note: this example used the
knitr hook functions
r linkfn("setupKnitr")) to insert the
scene into this vignette; the previous example used the
function. We generally
recommend the newer
r linkfn("rglwidget") approach.
Note that both
persp3d are generic functions,
with the following methods defined:
Adding Graphical Elements
Just as we have
r linkfn("points", pkg="graphics") and
r linkfn("lines", pkg="graphics") in classic graphics, there are a number
of low level functions in
rgl to add graphical elements to the
currently active plot. The "primitive" shapes are those that are
native to OpenGL:
||adds line segments|
Each of the above functions takes arguments
r linkfn("xyz.coords", pkg="grDevices") for flexibility.
They group successive entries
as necessary. For example, the
r linkfn("triangles3d") function takes each
successive triple of points as the vertices of a triangle.
You can use these functions to annotate the current graph, or to construct a figure from scratch.
rgl also has a number of objects which it constructs
from the primitives.
||adds straight lines to plot (like
||adds spherical arcs or spirals to plot|
||adds planes to plot|
||add clipping planes to plot|
||add sprites (fixed shapes or images) to plot|
||a surface (as used in
||add an arrow to a scene|
||draw base-style plotting symbols|
Axes and other "decorations"
The following low-level functions control the look of the graph:
||add axes to plot|
||add box around plot|
||add title to plot|
||add marginal text to plot|
||add multiple "decorations" (scales, etc.) to plot|
||set the aspect ratios for the plot|
||set the background of the scene|
||show a 2D plot or image in a 3D scene|
||set a legend for the scene|
||add a reference grid to a graph|
||choose label positions to avoid overlap|
For example, to plot three random triangles, one could use
triangles3d(cbind(x=rnorm(9), y=rnorm(9), z=rnorm(9)), col = "green") decorate3d() bg3d("lightgray") aspect3d(1,1,1)
*3d functions mentioned above, there are even lower-level
r indexfns(c("rgl.primitive", "rgl.points", "rgl.linestrips", "rgl.lines", "rgl.triangles",
"rgl.quads", "rgl.texts", "rgl.abclines", "rgl.planes", "rgl.bg",
"rgl.clipplanes", "rgl.bbox", "rgl.spheres", "rgl.sprites", "rgl.surface")).
You should avoid using these functions, which do not work well with the higher level
*3d functions. See the
r linkfn("r3d", text="?r3d", pkg="rgl") help
topic for details.
Controlling the Look of the Scene
In most scenes, objects are "lit", meaning that their appearance depends on their position and orientation relative to lights in the scene. The lights themselves don't normally show up, but their effect on the objects does.
r indexfns("light3d") function to
specify the position and characteristics of a light.
Lights may be infinitely distant, or may be embedded
within the scene. Their characteristics include
specular components, all
defaulting to white. The
ambient component appears
the same from any direction. The
depends on the angle between the surface and the light,
specular component also takes the viewer's
position into account.
r indexfns("rgl.light") function is a lower-level
function with different defaults; users should normally
The mental model used in
rgl is that the objects being shown
in scenes are physical objects in space, with material properties
that affect how light reflects from them (or is emitted by them).
These are mainly controlled by the
r indexfns("material3d") function,
or by arguments to other functions that are passed to it.
The material properties that can be set by calls to
described in detail in the
r linkfn("material3d", text="?material3d", pkg="rgl") help page.
Here we give an overview.
|color||white||vector of surface colors to apply to successive vertices for diffuse light|
|alpha||1||transparency: 0 is invisible, 1 is opaque|
|lit||TRUE||whether lighting calculations should be done|
|ambient||black||color in ambient light|
|specular||white||color in specular light|
|emission||black||color emitted by the surface|
|shininess||50||controls the specular lighting: high values look shiny|
|smooth||TRUE||whether shading should be interpolated between vertices|
|texture||NULL||optional path to a "texture" bitmap to be displayed on the surface|
|front, back||fill||should polygons be filled, or outlined?|
|size||3||size of points in pixels|
|lwd||1||width of lines in pixels|
Other properties include
"texmipmap", "texmagfilter", "texminfilter", "texenvmap", "fog",
"point_antialias", "line_antialias", "depth_mask", "depth_test" and "polygon_offset";
r linkfn("material3d", "the help page", pkg = "rgl") for details.
There is also an
r indexfns("rgl.material") function that works
at a lower level; users should normally avoid it.
As described in the previous section, one of the material
texture, the name of a bitmap file (in
format) containing an image to be displayed on the surface.
This section gives more details about textures.
OpenGL, each vertex in a polygon may be associated with a
particular location in the bitmap. The interior of the
polygon interpolates within the bitmap. There are two
rgl functions for specifying these coordinates.
Functions which specify primitives (
r linkfn("triangles3d"), etc.) accept an optional matrix argument
texcoords which gives
s (horizontal) and
locations within the bitmap in columns with one row per vertex.
The coordinates are
(0,0) for the lower left, and
for the upper right. If values outside this range are given,
the image repeats, i.e.
(1.1, 1.1) would specify the same
point in the image as
Other functions such as
r linkfn("surface3d") that take
matrices for each vertex coordinate accept texture coordinates
as matrices as well, in arguments
For example, the
following code displays four copies of a 2D plot on a quad,
because the texture coordinates run from 0 to 2 in both
filename <- tempfile(fileext = ".png") png(filename = filename) plot(rnorm(1000), rnorm(1000)) dev.off() open3d() xyz <- cbind(c(0,1,1,0), 0, c(0,0,1,1)) quads3d(xyz, texture = filename, texcoords = xyz[,c(1, 3)]*2, col = "white", specular = "black") rglwidget()
Some other notes:
- The color in the figure above was specified to be white. By default,
the colors in the bitmap will modify the colour of the
colis black (a common default), you won't see anything.
- On the other hand, you usually don't want specular
reflections (which show up as glare). Setting
specularto black prevents those.
- How the bitmap is handled is controlled by the material
"textype". The default is
"rgb", which takes the red-green-blue colours from the bitmap and uses them to modify the corresponding colours in the polygon. Other possibilities for
"textype"are described in
r linkfn("material3d", "the material3d help page", pkg = "rgl").
- The other
"tex*"material properties control how the interpolation within the image is done.
OpenGLsupports 1- and 3-dimensional textures; these are not supported in
par3d: Miscellaneous graphical parameters
r indexfns("par3d") function, modelled after the classic
r linkfn("par", pkg="graphics") function, sets or reads
a variety of different
parameters. Some parameters are completely read-only; others are
fixed at the time the window is opened, and others may be changed
at any time.
|antialias||fixed||Amount of hardware antialiasing|
|cex||Default size for text|
|family||Device-independent font family name; see
|font||Integer font number|
|useFreeType||Should FreeType fonts be used if available?|
|fontname||read-only||System-dependent font name set by
|FOV||Field of view, in degrees. Zero means isometric perspective|
|maxClipPlanes||read-only||How many clip planes can be defined?|
|modelMatrix||read-only||The OpenGL ModelView matrix; partly set by
|projMatrix||read-only||The OpenGL Projection matrix|
|bbox||read-only||Current bounding-box of the scene|
|viewport||Dimensions in pixels of the scene within the window|
|windowRect||Dimensions in pixels of the window on the whole screen|
|listeners||Which subscenes respond to mouse actions in the current one|
|mouseMode||What the mouse buttons do. See
|observer||read-only||The position of the observer; set by
|scale||Rescaling for each coordinate; see
|zoom||Magnification of the scene|
r indexfns("r3dDefaults") list and the
function control defaults in new windows opened by
The function looks for the variable in the user's global environment, and if not found there, finds the one in the
rgl namespace. This
allows the user to override the default settings for new windows.
Once found, the
r3dDefaults list provides initial values for
r linkfn("par3d") parameters, as well as defaults for
r linkfn("material3d") and
r linkfn("bg3d") in components
Meshes: Constructing Shapes
rgl includes a number of functions to construct and display
various solid shapes. These generate objects of class
"shapelist3d". The details of the classes are
described below. We start with functions to generate them.
These functions generate specific shapes. Optional arguments allow attributes such as colour or transformations to be specified.
open3d() cols <- rainbow(7) layout3d(matrix(1:16, 4,4), heights=c(1,3,1,3)) text3d(0,0,0,"tetrahedron3d"); next3d() shade3d(tetrahedron3d(col=cols)); next3d() text3d(0,0,0,"cube3d"); next3d() shade3d(cube3d(col=cols)); next3d() text3d(0,0,0,"octahedron3d"); next3d() shade3d(octahedron3d(col=cols)); next3d() text3d(0,0,0,"dodecahedron3d"); next3d() shade3d(dodecahedron3d(col=cols)); next3d() text3d(0,0,0,"icosahedron3d"); next3d() shade3d(icosahedron3d(col=cols)); next3d() text3d(0,0,0,"cuboctahedron3d"); next3d() shade3d(cuboctahedron3d(col=cols)); next3d() text3d(0,0,0,"oh3d"); next3d() shade3d(oh3d(col=cols))
A very large collection of polyhedra is contained in the
r linkfn("Rpolyhedra-package", text = "Rpolyhedra", pkg = "Rpolyhedra")
Generating new shapes
These functions generate new shapes:
||generate a tube or cylinder|
||generate a flat polygon by triangulation|
||generate an "extrusion" of a polygon|
||generate a solid of rotation|
||generate an ellipsoid in various ways|
||generate a shape from vertices and faces|
||generate a shape by combining other shapes|
||a generic function; see below|
A related function is
r indexfns("triangulate"), which takes a
two dimensional polygon and divides it up into triangles using the
The generic function
is provided to allow data structures produced by
other code to be converted to mesh
structures. Currently the following classes
||Delaunay triangulations of irregular point clouds|
||Also Delaunay triangulations|
||Generalized Delaunay triangulations|
r indexfns("as.mesh3d.default") method is a simple way
to construct a mesh from a matrix of vertices; it can use
r indexfns("mergeVertices") (which can also be used on its own)
to merge repeated vertices within the matrix, allowing
r linkfn("addNormals") to be used to give a smooth appearance.
The underlying class structure for shapes
"shape3d" is the basic abstract type. Objects of this class can be
r indexfns("shade3d") (which shades faces),
r indexfns("wire3d") (which draws edges), or
(which draws points at each vertex.)
"mesh3d" is a descendant type. Objects of this type contain the following
|vb||A 4 by n matrix of vertices in homogeneous coordinates. Each column is a point.|
|it||(optional) A 3 by t matrix of vertex indices. Each column is a triangle.|
|ib||(optional) A 4 by q matrix of vertex indices. Each column is a quadrilateral.|
|material||(optional) A list of material properties.|
|normals||(optional) A matrix of the same shape as vb, containing normal vectors at each vertex.|
|texcoords||(optional) A 2 by n matrix of texture coordinates corresponding to each vertex.|
The final set of functions manipulate and modify mesh objects:
||add normal vectors to make a shape look smooth|
||add extra vertices to make it look even smoother|
||clip mesh object using curved boundary|
The individual steps in
r linkfn("subdivision3d") are also available:
r indexfns(c("deform.mesh3d", "divide.mesh3d", "normalize.mesh3d")). These
are mainly intended for internal use.
rgl has several functions to support displaying multiple different
"subscenes" in the same window. The high level functions are
||Multiple figures (like
||Multiple figures (like
||Move to the next figure (like
||List all the subscenes in the current layout|
||Clear the current list and revert to the previous one|
There are also lower level functions.
||Create a new subscene, with fine control over what is inherited from the parent|
||Report on the active subscene|
||Get information on current subscene|
||Make a different subscene active|
||Add objects to a subscene, or delete them|
||Do "garbage collection": delete objects that are not displayed in any subscene|
rgl detects and handles mouse clicks within your scene,
and uses these to control its appearance. You can find out the current
handlers using the following code:
c("left", "right", "middle") refer to the buttons on
a three button mouse, or simulations of them on other mice.
refers to the mouse wheel.
The button actions generally correspond to click and drag operations.
Possible values for
r indexfns("mouseMode", '<code>"mouseMode"</code>') for buttons or the wheel are as follows:
||The mouse acts as a virtual trackball. Clicking and dragging rotates the scene|
||The mouse affects rotations by controlling polar coordinates directly|
||The mouse is being used by the
||The mouse zooms the display|
||The mouse affects perspective by changing the field of view|
||Rotating the mouse wheel towards the user "pulls the scene closer"|
||The same rotation "pushes the scene away"|
||A user action set by
The following functions make use of the mouse for selection within a scene.
||like the classic graphics
||returns a function that tests whether a coordinate was selected|
||selects from specific objects|
r indexfns("rgl.select3d") function is an obsolete version of
r indexfns("rgl.select") is a low-level support
rgl has several functions that can be used to construct
animations. These are based on functions that update the
scene according to the current real-world time, and repeated
calls to those. The functions are:
||Repeatedly call the update function|
||Update the display by rotating at a constant rate|
||Compute new values of some
r linkfn("movie3d") function for a way to output an animation
to a file on disk.
Animations are not currently supported in the HTML written by
r linkfn("rglwidget"), though the
playwidget function provides equivalent functionality.
Integration with TCL/TK
There are three functions in
rgl that support control of an
scene using the TCL/TK framework.
||Set up buttons in a window to control a scene|
||Embed the control buttons in a separate TCL/TK frame|
||Create a dialog to interactively save mouse actions|
These functions were formerly contained (without the
tk prefixes on
their names) in the
tkrgl package. That package is now deprecated.
Exporting and importing scenes
rgl contains several functions to write scenes to disk for use
by other software, or to read them in.
In order from highest fidelity to lowest, the functions are:
||Save a scene to an R variable, which can be saved and reloaded|
||Write files for Asymptote|
||Write PLY files (commonly used in 3D printing)|
||Read or write OBJ files (commonly used in 3D graphics)|
||Read or write STL files (also common in 3D printing)|
There are also functions to save snapshots or other recordings of a scene, without any 3D information being saved:
||Save a PNG file bitmap of the scene|
||Save a Postscript, LaTeX, PDF, SVG or PGF vector rendering of the scene|
||Save a series of bitmaps to be assembled into a movie|
||Obtain pixel-level information about the scene in an R variable|
||Driver function for inserting a snapshot into a Sweave document.|
||Function to set up
r indexfns("rgl.snapshot") function is identical to
r indexfns(c("rgl.Sweave.off", "Sweave.snapshot")) are
involved in Sweave processing and not normally called by users.
There are two ways in which
rgl scenes are normally
displayed within R. The older one is in a dedicated
window. In Unix-alikes this is an X11 window; it is
a native window in Microsoft Windows. On MacOS, the
XQuartz system (see http://xquartz.org) needs to be
installed to support this.
To suppress this display, set
options(rgl.useNULL = TRUE) before opening a new
rgl window. See
the help page for the
r indexfns("rgl.useNULL") function
for how to set this before starting R.
The newer way to display a scene is by using WebGL
in a browser window or in the Viewer pane in RStudio.
To select this, set
options(rgl.printRglwidget = TRUE).
Each operation that would change the scene will
return a value which triggers a new WebGL display
Working with WebGL scenes
There are currently two schemes for exporting a scene to a web page.
The recommended approach works with the
(see http://www.htmlwidgets.org/). In an R Markdown document
knitr, use the
r indexfns("rglwidget") function. (You can also use
webgl=TRUE; we recommend the explicit use of
rglwidget.) This approach also
allows display of
rgl scenes in
rgl scenes, various controls for them can
be displayed, and there are a few utility functions
that can be useful:
||set individual properties|
||control a clippling plane|
||control which objects are displayed|
||"age" vertices of an object|
||control properties of vertices|
||WebGL control like
||display and automate controls|
||display a button to toggle some items|
||get or set
||Dimensions of figures in R Markdown document|
||share data using
||change mouse mode in rgl scene|
||arrange multiple objects in an HTML display|
Some functions are mainly for internal use:
r indexfns(c("elementId2Prefix", "playwidgetOutput", "renderPlaywidget", "rglwidgetOutput", "renderRglwidget", "registerSceneChange")).
More details are given in the vignette
User Interaction in WebGL.
r indexfns(c("lowlevel", "highlevel", "rglId")) are also for internal use,
marking function results for automatic
printing. Finally, the experimental function
r indexfns("setUserShaders") allows you to
use hand-written shaders in WebGL.
The older approach uses the
writeWebGL function to export a scene
||insert a slider to make changes to a scene|
||insert a slider to control a clipping plane|
||insert a slider to control which objects are displayed|
||insert a button to toggle some items|
||function to modify properties|
||function to choose subsets|
||function to "age" vertices|
||function to modify individual vertices|
||function to modify matrices|
Working with the scene
rgl maintains internal structures for all the scenes it displays.
The following functions allow users to find information about them
and manipulate them.
||open a new window|
||close the current window|
||bring the current window to the top|
||id of the active device|
||ids of all active devices|
||set a particular device to be active|
||ids and types of all current objects|
||attributes of objects in the scene|
||delete an object from the scene|
||delete all objects of certain classes|
||return information about the current projection|
||convert between coordinates in the current projection|
r indexfns("as.triangles3d") generic function is intended to
extract coordinates in a form suitable for passing to
r linkfn("triangles3d"). Currently a method is provided for
r linkfn("rglId") objects.
In addition to these, there are some other related functions which
should rarely be called by users:
r indexfns(c("rgl.init", "rgl.open", "rgl.quit")).
Working with 3-D vectors
rgl functions work internally with "homogeneous" coordinates.
In this system, 3-D points are represented with 4 coordinates, generally
called (x, y, z, w). The corresponding Euclidean point is
(x/w, y/w, z/w), if w is nonzero; zero values of w correspond to
"points at infinity". The advantage of this system is that
affine transformations including translations and perspective shifts
become linear transformations, with multiplication by a 4 by 4 matrix.
rgl has the following functions to work with homogeneous coordinates:
||convert between homogeneous and Euclidean coordinates|
||apply a transformation|
||apply a general transformation|
||compute the transformation matrix|
||return a 4 x 4 identity matrix|
There is also a function
r indexfns("GramSchmidt"), mainly for internal
use: it does a Gram-Schmidt orthogonalization of a 3x3 matrix,
with some specializations for its use in
Working with other packages
Sometimes it may be convenient to interactively
rotate a scene to a particular view, then
display it in
lattice or base graphics.
r indexfns("rglToLattice") and
r indexfns("rglToBase") functions support this.
For example, we first display the volcano data in
rgl.close() persp3d(volcano, col = "green") rglwidget()
This display is interactive, but we can reproduce the initial view using the
r linkfn("wireframe", pkg = "lattice") or base graphics
r linkfn("persp", pkg = "graphics") functions:
lattice::wireframe(volcano, col = "green", screen = rglToLattice()) angles <- rglToBase() persp(volcano, col = "green", shade = TRUE, theta = angles$theta, phi = angles$phi)
Note that the
orientlib package must be
available for these functions to work.
Warning: Work in Progress!
This vignette is always a work in progress. Some aspects of the
package are not described, or do not have examples. There may
even be functions that are missed completely, if the following
list is not empty:
Index of Functions
The following functions and constants are described in this document:
writeIndex(cols = 5)