Categories: TutorialsData

How to create 3D Graphics and Animation in R

4 min read

[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)

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

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

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")

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")

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.

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)

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)

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"))

[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.

 

Savia Lobo

A Data science fanatic. Loves to be updated with the tech happenings around the globe. Loves singing and composing songs. Believes in putting the art in smart.

View Comments

  • hello.
    my name is maryam my thesis master about graphics and animation in R, Do you have any good books, or articles about this topic?Im thankful for everything :)

    can you help me?😢

Share
Published by
Savia Lobo

Recent Posts

Top life hacks for prepping for your IT certification exam

I remember deciding to pursue my first IT certification, the CompTIA A+. I had signed…

3 years ago

Learn Transformers for Natural Language Processing with Denis Rothman

Key takeaways The transformer architecture has proved to be revolutionary in outperforming the classical RNN…

3 years ago

Learning Essential Linux Commands for Navigating the Shell Effectively

Once we learn how to deploy an Ubuntu server, how to manage users, and how…

3 years ago

Clean Coding in Python with Mariano Anaya

Key-takeaways:   Clean code isn’t just a nice thing to have or a luxury in software projects; it's a necessity. If we…

3 years ago

Exploring Forms in Angular – types, benefits and differences   

While developing a web application, or setting dynamic pages and meta tags we need to deal with…

3 years ago

Gain Practical Expertise with the Latest Edition of Software Architecture with C# 9 and .NET 5

Software architecture is one of the most discussed topics in the software industry today, and…

3 years ago