How to Create 3D Plots in R (With Examples)

Creating 3D plots in R requires the use of the package ‘rgl’. This package allows you to create 3D plots by specifying the coordinates of the points, lines, and surfaces to be plotted. Once the points are specified, you can then add color, lighting, and other graphical features to enhance the plot. Additionally, you can use a variety of functions to manipulate and visualize the data in 3D, such as rotating the plot and plotting multiple objects. Examples of 3D plots created with the ‘rgl’ package can be found in the R documentation.


The easiest way to create a 3D plot in R is to use the persp() function.

persp(x, y, z)

The following examples show how to use this function in practice.

Example 1: Basic 3D Plot

The following code shows how to create a basic 3D plot:

#define x and y
x <- -10:10
y <- -10:10

#define function to create z-values
z_values <- function(x, y) {
  sqrt(x ^ 2 + y ^ 2)
}

#create z-values
z = outer(x, y, z_values)

#create 3D plot
persp(x, y, z)

Example 2: Custom 3D Plot

The following code shows how to customize the axis labels, title, color, and shade of the plot:

#define x and y
x <- -10:10
y <- -10:10

#define function to create z-values
z_values <- function(x, y) {
  sqrt(x ^ 2 + y ^ 2)
}

#create z-values
z = outer(x, y, z_values)

#create 3D plot
persp(x, y, z, xlab='X Variable', ylab='Y Variable', zlab='Z Variable',
      main='3D Plot', col='pink', shade=.4)

3D plot in R

Example 3: Rotate the 3D Plot

The following code shows how to rotate the 3D plot to make it easier to view, using the theta and phi arguments:

#define x and y
x <- -10:10
y <- -10:10

#define function to create z-values
z_values <- function(x, y) {
  sqrt(x ^ 2 + y ^ 2)
}

#create z-values
z = outer(x, y, z_values)

#create 3D plot
persp(x, y, z, xlab='X Variable', ylab='Y Variable', zlab='Z Variable',
      main='3D Plot', col='pink', shade=.4, theta = 30, phi = 15)

Example 4: Add Tick Marks to the 3D Plot

The following code shows how to use the ticktype argument to add tick marks with labels to each axis:

#define x and y
x <- -10:10
y <- -10:10

#define function to create z-values
z_values <- function(x, y) {
  sqrt(x ^ 2 + y ^ 2)
}

#create z-values
z = outer(x, y, z_values)

#create 3D plot
persp(x, y, z, xlab='X Variable', ylab='Y Variable', zlab='Z Variable',
      main='3D Plot', col='pink', shade=.4, theta = 30, phi = 15, ticktype='detailed')

The following tutorials explain how to create other common charts in R:

x