14.7 C
London
Tuesday, July 2, 2024
HomeStatistics TutorialRHow to Create 3D Plots in R (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 #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 #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 #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 #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')

Additional Resources

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

How to Plot Multiple Lines in One Chart in R
How to Plot Multiple Boxplots in One Chart in R
How to Create a Pareto Chart in R
How to Create Radar Charts in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories