When dealing with complex datasets, having the possibility to show your data in a 3D environment can be really enhancing.
This recipe will show you how to create such a plot, animate it, and export your animation as a GIF.
This recipe will leverage the rgl
package specifically developed for 3D visualizations in R:
install.packages("rgl") library(rgl)
We will also need to install ImageMagick in order to perform the export into the GIF format.
You can find instructions for software installation at http://www.imagemagick.org/script/binary-releases.php.
As an explicative dataset, we will use the iris
dataset, which is a built-in dataset available with all base R installations.
The iris
dataset is one of the most used datasets in R tutorials and learning sessions, and it is derived from a 1936 paper by Ronald Fisher, named The use of multiple measurements in taxonomic problems.
Data was observed on 50 samples of 3 species of the iris flower:
On each sample, four features were recorded:
The plot3d()
function lets you easily create and visualize a 3D plot, specifying which data is to be used for each one of three dimensions. The function can be seen as a 3D version of the base R plot()
function:
plot3d(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length, type = "p", col = as.numeric(iris$Species),size = 10)
This code will result in the following 3D plot:
main
argument in the plot3d()
function:plot3d(iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length, type = "p", col = as.numeric(iris$Species),size = 10, main = "iris dataset visualization")
spin3d()
and play3d()
functions, where the first specifies rotation and velocity, and the latter adds a duration argument to set the number of seconds of automatic animation:play3d(spin3d(axis = c(0, 0, 1), rpm = 20), duration = 2)
This code will result in the opening of a small window that shows the previously seen plot rotating for two seconds. Beware that by changing the axis parameter, you can change the axis on which the plot will rotate.
play3d(spin3d(axis = c(0, 0, 1), rpm = 20), duration = 10)
movie3d()
function to which we pass the spin3d()
function and a duration argument in a way similar to what we have seen for the play3d()
function:movie3d(spin3d(axis = c(0, 0, 1), rpm = 20),duration = 3, movie = "the_movie_name_without_extension")
As a result, a .gif
file will be created in your current directory, and it will be named as per the value of the movie argument.