Examples to Create 3D Plots and Animation in R
Now let us see a few examples to understand the concept.
Perspective Plot
In this example, we first generated some data and then plot it on the graphs using the persp3d() method, which takes the x, y, and z coordinates and a ‘col’ argument that defines the color of the graph.
R
# import and load rgl package install.packages ( "rgl" ) library (rgl) # Generate some sample data x <- seq (-5, 6, by = 0.1) y <- seq (-5, 7, by = 0.1) z <- outer (x, y, function (x, y) dnorm ( sqrt (x^2 + y^2))) # Create a 3D surface plot persp3d (x, y, z, col = "blue" ) # add animation play3d ( spin3d (axis = c (0, 0, 1)), duration = 10) |
Output:
Scatter Plot
In this example, we take R’s inbuilt dataset ‘iris’ as the input and then plot it on the graphs using the plot3d() method, which is used to plot the scatterplots. It takes the Sapel Length, Sapel Width, and Petal Length as the x, y, and z coordinates respectively, a ‘col’ argument that defines the color of the graph, size of the points of the scatterplots, and type as ‘s’ which means spheres.
R
# import and load rgl package install.packages ( "rgl" ) library (rgl) # load the set data (iris) # plot the 3D graph plot3d (iris$Sepal.Length, iris$Sepal.Width, iris$Petal.Length, col = "red" , size = 3, type = "s" ) # add animations play3d ( spin3d (axis = c (0, 0, 1)), duration = 10) |
Output:
How to create 3D Plots and Animations in R using rgl Package
The R programming language provides a powerful set of tools and packages for creating interactive 3D plots and animations. One such package is RGL. In this article, let us learn How to create 3D plots and animations using the RGL package.