假设我有一个由以下代表的3D点云:
arv = data.frame(axis_x = rnorm(n=300, mean=-0.20, sd=1.01),
axis_y = rnorm(n=300, mean=-0.45, sd=0.97),
elevation = rnorm(n=300, mean=-813.2, sd=13.89))
我还有一个抛物面模型:
model = lm(formula = elevation ~ (axis_x + axis_y)^2 + I(axis_x^2) + I(axis_y^2), data = arv)
是否可以通过某种方式在3D图中将两者(点和模型)一起绘制?
答案 0 :(得分:5)
可以使用persp()
和trans3d
来完成此操作。为了提高清晰度,有助于使用以下行将观察值连接到函数的3d表面:
# data
arv = data.frame(axis_x = rnorm(n=300, mean=-0.20, sd=1.01),
axis_y = rnorm(n=300, mean=-0.45, sd=0.97),
elevation = rnorm(n=300, mean=-813.2, sd=13.89))
# fit
model = lm(formula = elevation ~ (axis_x + axis_y)^2 + I(axis_x^2) + I(axis_y^2), data = arv)
# grid for plotting function
x <- seq(min(arv$axis_x), max(arv$axis_x), length.out = 20)
y <- seq(min(arv$axis_y), max(arv$axis_y), length.out = 20)
# function for predicted surface from model
f <- function(x, y) { cbind(1,x,y,x^2,y^2,x*y) %*% coef(model) }
# predicted values in form that persp() can use
z <- outer(x, y, f)
# 3d plot of surface with persp()
ele_3d <- persp(x=x,y=y,z=z, theta=40, phi=15, zlim=c(min(arv$elevation), max(arv$elevation)) )
# transform observed values into 2d space
elevation_points <- trans3d(arv$axis_x, arv$axis_y, arv$elevation, pmat=ele_3d)
# plot observed values
points(elevation_points)
# add dotted lines from surface to observed values
fit_vals <- trans3d(arv$axis_x, arv$axis_y, fitted(model), pmat = ele_3d)
segments(fit_vals$x, fit_vals$y, elevation_points$x, elevation_points$y, lty = 3)
另一种选择是在格子中使用wireframe()
的面板函数。请参阅this post。