Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

How to create 3D Graphics and Animation in R

Save for later
  • 4 min read
  • 23 Nov 2017

article-image

[box type="note" align="alignright" class="" width=""] The article is originally extracted from our book R Data Analysis Cookbook - Second Edition by Kuntal Ganguly. Data analytics with R has emerged to be a very important focus for organizations of all kind. The book will show how you can put your data analysis skills in R to practical use. It contains recipes catering to basic as well as advanced data analysis tasks. [/box]

In this article, we have captured one aspect of using R for the creation of 3D graphics and animation. When, a two-dimensional view is not sufficient to understand and analyze the data; besides the x, y variable, an additional data dimension can be represented by a color variable. Our article gives a step by step explanation on how to plot 3D package in R is used to visualize three-dimensional graphs. Codes and data files are readily available for download towards the end of the post.

Get set ready

Make sure you have downloaded the code and the mtcars.csv file is located in the working directory of R. Install and load the latest version of the plot3D package:

> install.packages("plot3D")
> library(plot3D)

How to do it...

  1. Load the mtcars dataset and preprocess it to add row names and remove the model name column:
> mtcars=read.csv("mtcars.csv")
> rownames(mtcars) <- mtcars$X
> mtcars$X=NULL
> head(mtcars)

3d-graphics-animation-r-img-0

2. Next, create a three-dimensional scatter plot:

> scatter3D(x=mtcars$wt, y=mtcars$disp, z=mtcars$mpg, clab =
c("Miles/(US) gallon"))

3d-graphics-animation-r-img-1

3. Now, add title and axis labels to the scatter plot:

> scatter3D(x=mtcars$wt, y=mtcars$disp, z=mtcars$mpg, pch = 18,
theta = 20, phi = 20, main = "Motor Trend Car Road Tests", xlab =
"Weight lbs",ylab ="Displacement (cu.in.)", zlab = "Miles gallon")

3d-graphics-animation-r-img-2

Rotating a 3D plot can provide a complete view of the data. Now view the plot in different directions by altering the values of two attributes--theta and phi:

> scatter3D(x=mtcars$wt, y=mtcars$disp, z=mtcars$mpg,clab = c("Cars
Mileage"),theta = 15, phi = 0, bty ="g")

3d-graphics-animation-r-img-3

How it works...

The scatter3D() function from the plot3D package has the following parameters:

  • x, y, z: Vectors of point coordinates
  • colvar: A variable used for the coloring
  • col: A color palette to color the colvar variable
  • labels: Refers to the text to be written
  • add: Logical; if TRUE, then the points will be added to the current plot, and if FALSE, a new plot is started
  • pch: Shape of the points
  • cex: Size of the points
  • theta: The azimuthal direction
  • phi: Co-latitude; both theta and phi can be used to define the angles for the viewing direction
  • Bty: Refers to the type of enclosing box and can take various values such as f-full box, b-default value (back panels only), g- grey background with white grid lines, and bl- black background

There's more…

The following concepts are very important for this recipe.

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at R$50/month. Cancel anytime

Adding text to an existing 3D plot

We can use the text3D() function to add text based on the car model name, alongside the data points:

> scatter3D(x=mtcars$wt, y=mtcars$disp, z=mtcars$mpg, phi = 0, bty = "g",
pch = 20, cex = 0.5)
> text3D(x=mtcars$wt, y=mtcars$disp, z=mtcars$mpg, labels =
rownames(mtcars), add = TRUE, colkey = FALSE, cex = 0.5)

3d-graphics-animation-r-img-4

Using a 3D histogram

The three-dimensional histogram function, hist3D(), has the following attributes:

  • z: Values contained within a matrix.
  • x, y: Vectors, where the length of x should be equal to nrow(z) and length of y should be equal to ncol(z).
  • colvar: Variable used for the coloring and has the same dimension as z.
  • col: Color palette used for the colvar variable. By default, a red-yellow-blue color scheme.
  • add: Logical variable. If TRUE, adds surfaces to the current plot. If FALSE, starts a new plot.

Let's plot the Death rate of Virgina using a 3D histogram:

data(VADeaths)
hist3D(z = VADeaths, scale = FALSE, expand = 0.01, bty = "g", phi = 20, col
= "#0085C2", border = "black", shade = 0.2, ltheta = 80, space = 0.3,
ticktype = "detailed", d = 2)

3d-graphics-animation-r-img-5

Using a line graph

To visualize the plot with a line graph, add the type parameter to the scatter3D() function. The type parameter can take the values l(only line), b(both line and point), and h(horizontal line and points both).

The 3D plot with a horizontal line and plot:

> scatter3D(x=mtcars$wt, y=mtcars$disp, z=mtcars$mpg,type="h", clab =
c("Miles/(US) gallon"))

3d-graphics-animation-r-img-6

[box type="download" align="" class="" width=""]Download code files here. [/box]

If you think the recipe is delectable, you should definitely take a look at R data Analysis Cookbook- Second edition which will enlighten you more on data visualizations with R.3d-graphics-animation-r-img-7