3D plotly Graph in R (3 Examples)

 

Hi! This tutorial will show you how to build 3D plotly graphs in the R programming language.

We will be building a 3D scatter plot, 3D line plot, and a 3D mesh plot.

Here is an overview:

Let’s dive into the R code!

 

Install & Load plotly & dplyr

To install and load the R plotly library and dplyr library, we will need to run the code below in either the R Studio IDE or in any other preferred code editor that can run R:

# install plotly & dplyr
install.packages(c("plotly", "dplyr"))
 
# load plotly & dplyr
library(plotly)
 
library(dplyr)

The dplyr library is the foremost library in R programming for data analysis and data manipulation, and it also enables us to use the pipe operator to pipe lines of code together and run them in one chunk.

Now, with plotly and dplyr installed and loaded into our R environment, we can go on to create our example dataset.
 

Create Demo Dataset

We will make use of the mtcars dataset, which comes pre-loaded inside R Studio. But if you are not using R Studio, you can download the dataset as a CSV file here.

Save the file in your current working directory, then run the code below to load it into your R environment:

mtcars = read.csv("path to csv file")

You can preview the first 10 rows of the dataset if you want by running mtcars |> head(10).

With the example dataset loaded, we can now build 3D visualizations!
 

Example 1: Build 3D Scatter Plot

In this first example, we will build a 3D scatter plot. Therefore, run the code below to build the plot:

fig <- mtcars |> 
  plot_ly(x = ~mpg, y = ~disp, z = ~hp) |> 
  add_markers() |> 
  layout(scene = list(xaxis = list(title = "Mile Per Gallon"),
                      yaxis = list(title = "Displacement"),
                      zaxis = list(title = "Horse Power")),
         annotations = list(
           x = 1.13,
           y = 1.05,
           text = 'Miles/(US) gallon',
           xref = 'paper',
           yref = 'paper',
           showarrow = FALSE
         ))
 
fig


In the above example, we passed the mtcars data frame to the plot_ly() function, and defined the x, y, and z axes using the columns of interest in the data frame. Next, we added markers to the plot using the add_markers() function.

Finally, we formatted the plot layout using the layout() function. In that function, we passed a list defining the axis labels for the plot and also passed a list for annotating the plot as well, which displays information when you hover over the plot.
 

Example 2: Build 3D Line Plot

In this next example, we will build a 3D line plot. Run the code below to do so:

fig <- mtcars |> 
  plot_ly(x = ~mpg, y = ~disp,z = ~hp, type = "scatter3d", mode = "lines",
          opacity = 1, line = list(width = 6, color = "green"))
 
fig


In the plot_ly() function above, we used the same x, y, and z axes arguments as in the previous example, but here we defined the type of the plot as “scatter3d” and then set the modes = argument to “lines” in order to create a line plot.

Next, we passed a list specifying the width and color of the line plot to the line = argument in order to style the plot.

 

Example 3: Build 3D Mesh Plot

In this final example, we will build a 3D mesh plot. Run the code below in your IDE to build it:

fig <- mtcars |> 
  plot_ly(x = ~mpg, y = ~disp, z = ~hp, type = "mesh3d")
 
fig


As you can see, the code to build the mesh plot is a very simple one. All we needed to do was define the x, y, and z axes in the plot_ly() function, and specify the type of plot we want to build as “mesh3d”.
 

Video, Further Resources & Summary

Do you need more explanations on how to build 3D graphs in R? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain how to build 3D graphs in R.

 

The YouTube video will be added soon.

 

I hope you found this tutorial helpful! If yes, then make sure to check out other interesting R plotly tutorials on Statistics Globe, such as these ones:

This post has shown how to build 3D graphs in R. One feature that makes it interesting to visualize data as 3D plots is that they can be panned. This means you can right-click and hold down your mouse, then drag it around in order to get 360-degree views of your 3D plots. That way, you get a holistic view of your data points.

In case you have further questions, you may leave a comment below.

 

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top