Skip to content
Prev 180091 / 398506 Next

Response surface plot

On 5/12/2009 8:43 AM, Tim Carnus wrote:
I'm not aware of anyone who has done this.  The way to do the surface in 
rgl would be to construct a mesh of triangles using tmesh3d, and set the 
color of each vertex as part of the material argument. It's a little 
tricky to get the colors right when they vary by vertex, but the code 
below gives an example.

I would construct the mesh by starting with one triangle and calling 
subdivision3d, but you may want more control over them.

For example:

library(rgl)

# First create a flat triangle and subdivide it
triangle <- c(0,0,0,1, 1,0,0,1, 0.5, sqrt(3)/2, 0, 1)
mesh <- tmesh3d( triangle, 1:3, homogeneous=TRUE)
mesh <- subdivision3d(mesh, 4, deform=FALSE, normalize=TRUE)

# Now get the x and y coordinates and compute the surface height
x <- with(mesh, vb[1,])
y <- with(mesh, vb[2,])
z <- x^2 + y^2
mesh$vb[3,] <- z

# Now assign colors according to the height; remember that the
# colors need to be in the order of mesh$it, not vertex order.

vcolors <- rainbow(100)[99*z+1]
tricolors <- vcolors[mesh$it]
mesh$material = list(color=tricolors)

# Now draw the surface, and a rudimentary frame behind it.

shade3d(mesh)
triangles3d(matrix(triangle, byrow=TRUE, ncol=4), col="white")
quads3d(matrix(c(1,0.5,0.5,1, 0,sqrt(3)/2, sqrt(3)/2,0, 0,0,1,1), 
ncol=3), col="white")
bg3d("gray")

Duncan Murdoch