Gorgens
Gorgens

Reputation: 448

Overlay surface to 3d points

Suppose I have a 3D point cloud represented by:

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))

And I also have a paraboloid modeled by:

model = lm(formula = elevation ~ (axis_x + axis_y)^2 + I(axis_x^2) + I(axis_y^2), data = arv)

Is it some way to plot both (the points and model) together in a 3D plot?

Upvotes: 1

Views: 1378

Answers (1)

Nate Pope
Nate Pope

Reputation: 1706

This can be done with persp() and trans3d. To improve clarity, it helps to connect the observed values to the 3d surface of the function with lines:

# 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)

Another option is to use a panel function with wireframe() in lattice. See this post.

Upvotes: 5

Related Questions