Plotting voxels in R

Voxels are like 3d pixels and useful for various visualization tasks. I had some neuron-voxel data I wanted to plot. I also wanted this plot to be interactive such that I could freely rotate and zoom it to get a better sense of what was going on. The following MWE achieves this:

library(rgl)

#Generate a random set of voxel coordinates
data<-expand.grid(1:4,1:4,1:4)
data<-data[sample(nrow(data),20,replace=FALSE),]

#Generate random values
data$v<-runif(20)

#Give everything pretty names
colnames(data)<-c('x','y','z','v')

#Generate a colour gradient
cols<-heat.colors(100)

#Clear the display in case there's something else on it
rgl.clear()

#Set background colour
bg3d('white')

for(j in 1:20){ #For each voxel
  col<-ceiling(length(cols)*data$v[j])
  cubit = cube3d(color=col, alpha=0.3)
  cubit$vb[cubit$vb == -1] = 0
  cubit$vb[1,]      = cubit$vb[1,]+data$x[j]
  cubit$vb[2,]      = cubit$vb[2,]+data$y[j]
  cubit$vb[3,]      = cubit$vb[3,]+data$z[j]
  shade3d(cubit,add = TRUE,alpha=0.5)      
  wire3d (cubit,add = TRUE,color=col)
}

#Capture the current camera angle
pp1<-par3d(no.readonly=TRUE)

#Go to a captured camera angle
par3d(pp1)

#Save the image to a file
snapshot3d("image3d.png")

links