Skip to content
Prev 171233 / 398506 Next

3D or 4D plot

On 2/20/2009 1:55 PM, Duncan Murdoch wrote:
But it's Friday, so fun things like that are worth doing.  Here's some 
code to draw a bunch of cubes with a variety of colours.  Elaborate on 
it if you like.

Duncan Murdoch

cubes3d <- function(x,y,z,col="red",size=0.9,plot=TRUE) {

     xyz <- xyz.coords(x, y, z, recycle = TRUE)
     x <- xyz$x
     y <- xyz$y
     z <- xyz$z

     col <- rep(col, len=length(x))
     size <- rep(size/2, len=length(x))

     result <- list(vb=matrix(0, 4, 0), ib=matrix(1L, 4, 0), 
primitivetype="quad",
                    material=list(color=NULL, normals=NULL))
     class(result) <- "qmesh3d"

     for (i in seq_along(x)) {
        cube <- translate3d(scale3d(cube3d(), size[i], size[i], 
size[i]), x[i], y[i], z[i])
        offset <- ncol(result$vb)
        result$vb <- cbind(result$vb, cube$vb)
        result$ib <- cbind(result$ib, cube$ib + offset)
        result$material$color <- c(result$material$color, rep(col[i], 
4*ncol(cube$ib)))
     }
     if (plot)
        shade3d(result)
     invisible(result)
}

x <- rep(1:5, each=25)
y <- rep(rep(1:5, each=5), 5)
z <- rep(1:5, 25)
cubes3d(x,y,z,col=terrain.colors(125))