Creating 3D Plots in R Programming – persp() Function
3D plot in R Language is used to add title, change viewing direction, and add color and shade to the plot. The persp() function which is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane. persp() is defines as a generic function. Moreover, it can be used to superimpose additional graphical elements on the 3D plot, by lines() or points(), using the function trans3d().
persp() Function in R Programming Language
Syntax: persp(x, y, z)
Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining the location along x- and y-axis. z-axis will be the height of the surface in the matrix z.
Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z, t).
Example 1: Simple Right Circular Cone
R
cone <- function (x, y){
sqrt (x ^ 2 + y ^ 2)
}
x <- y <- seq (-1, 1, length = 30)
z <- outer (x, y, cone)
persp (x, y, z)
|
Output:
Here in the above code, function seq() to generate a vector of equally spaced numbers. The outer() function to apply the function cone at every combination of x and y.
Example 2: Adding Titles and Labeling Axes to Plot
Python3
cone < - function(x, y){
sqrt(x ^ 2 + y ^ 2 )
}
x < - y < - seq( - 1 , 1 , length = 30 )
z < - outer(x, y, cone)
persp(x, y, z,
main = "Perspective Plot of a Cone" ,
zlab = "Height" ,
theta = 30 , phi = 15 ,
col = "orange" , shade = 0.4 )
|
Output:
Here in the above code, xlab, ylab, and zlab can be used to label the three axes. Theta and phi are viewing direction.
Example 3: Visualizing a simple DEM(Digital elevation model)
Python3
z < - 2 * volcano
x < - 10 * ( 1 :nrow(z))
y < - 10 * ( 1 :ncol(z))
par(bg = "gray" )
persp(x, y, z, theta = 135 , phi = 30 ,
col = "brown" , scale = FALSE,
ltheta = - 120 , shade = 0.75 ,
border = NA, box = FALSE)
|
Output:
Example : 3D plots using the persp() function. Here’s an example of how to use it.
R
x <- seq (-5, 5, length.out = 50)
y <- seq (-5, 5, length.out = 50)
z <- outer (x, y, function (x, y) sin ( sqrt (x^2 + y^2))/ sqrt (x^2 + y^2))
persp (x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue" )
|
output :
Last Updated :
11 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...