[R] 3D or 4D plot

Duncan Murdoch murdoch at stats.uwo.ca
Fri Feb 20 20:28:43 CET 2009


On 2/20/2009 1:55 PM, Duncan Murdoch wrote:
> On 2/20/2009 1:46 PM, kapo coulibaly wrote:
>> Ideally I would want it to look like a rubik cube with each little cube
>> color coded based on the fourth column (data column). Your suggestion might
>> work if I could color code based on data in the fourth column.
>> Thanks
> 
> There's no primitive "cube" symbol in rgl, but you can get an array of 
> colour-coded spheres:
> 
> x <- rep(1:3, each=9)
> y <- rep(rep(1:3, each=3), 3)
> z <- rep(1:3, 9)
> colours <- terrain.colors(27)
> plot3d(x,y,z,col=colours, type="s", size=10)
> 
> If you really want cubes, you can put them together (start with cube3d() 
> to get one, and build on that), but it's a lot of work.

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




More information about the R-help mailing list