在 R 编程中创建 3D 绘图 - persp()函数
R 语言中的 3D 绘图用于添加标题、更改查看方向以及为绘图添加颜色和阴影。 persp()函数用于在透视图中创建 3D 表面。此函数将在 x-y 平面上绘制表面的透视图。 persp() 被定义为通用函数。此外,它还可以使用函数trans3d() 通过lines() 或 points() 在 3D 绘图上叠加其他图形元素。
R 编程语言中的 persp()函数
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).
示例 1:简单的正圆锥
R
# To illustrate simple right circular cone
cone <- function(x, y){
sqrt(x ^ 2 + y ^ 2)
}
# prepare variables.
x <- y <- seq(-1, 1, length = 30)
z <- outer(x, y, cone)
# plot the 3D surface
persp(x, y, z)
Python3
# Adding Titles and Labeling Axes to Plot
cone <- function(x, y){
sqrt(x ^ 2 + y ^ 2)
}
# prepare variables.
x <- y <- seq(-1, 1, length = 30)
z <- outer(x, y, cone)
# plot the 3D surface
# Adding Titles and Labeling Axes to Plot
persp(x, y, z,
main="Perspective Plot of a Cone",
zlab = "Height",
theta = 30, phi = 15,
col = "orange", shade = 0.4)
Python3
# Visualizing a simple DEM model
z <- 2 * volcano # Exaggerate the relief
x <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)
y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)
# Don't draw the grid lines : border = NA
par(bg = "gray")
persp(x, y, z, theta = 135, phi = 30,
col = "brown", scale = FALSE,
ltheta = -120, shade = 0.75,
border = NA, box = FALSE)
输出:
在上面的代码中,函数seq() 生成一个等距数字的向量。 outer()函数在 x 和 y 的每个组合上应用函数cone。
示例 2:为绘图添加标题和标签轴
Python3
# Adding Titles and Labeling Axes to Plot
cone <- function(x, y){
sqrt(x ^ 2 + y ^ 2)
}
# prepare variables.
x <- y <- seq(-1, 1, length = 30)
z <- outer(x, y, cone)
# plot the 3D surface
# Adding Titles and Labeling Axes to Plot
persp(x, y, z,
main="Perspective Plot of a Cone",
zlab = "Height",
theta = 30, phi = 15,
col = "orange", shade = 0.4)
输出:
在上面的代码中,可以使用xlab、ylab和zlab来标记三个轴。 Theta 和 phi 是观察方向。
示例 3:可视化一个简单的 DEM(数字高程模型)
Python3
# Visualizing a simple DEM model
z <- 2 * volcano # Exaggerate the relief
x <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)
y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)
# Don't draw the grid lines : border = NA
par(bg = "gray")
persp(x, y, z, theta = 135, phi = 30,
col = "brown", scale = FALSE,
ltheta = -120, shade = 0.75,
border = NA, box = FALSE)
输出: