13.10 Animating a Three-Dimensional Plot

13.10.1 Problem

You want to animate a three-dimensional plot by moving the viewpoint around the plot.

13.10.2 Solution

Rotating a 3D plot can provide a more complete view of the data. To animate a 3D plot, use play3d() with spin3d():

13.10.3 Discussion

By default, the graph will be rotated on the z (vertical) axis, until you send a break command to R.

You can change the rotation axis, rotation speed, and duration:

To save the movie, use the movie3d() function in the same way as play3d(). It will generate a series of .png files, one for each frame, and then attempt to combine them into a single animated .gif file using the convert program from the ImageMagick image utility.

This will spin the plot once in 15 seconds, at 50 frames per second:

The output file will be saved in a temporary directory, and the name will be printed on the R console.

If you don’t want to use ImageMagick to convert the output to a .gif, you can specify convert=FALSE and then convert the series of .png files to a movie using some other utility.