Richbits

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)

#We now have data of the form x,y,z,value

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

#Set background colour
bg3d('white')

for(j in 1:nrow(data)){                      #For each voxel
  #Values are in range [0,1]. Multiply be len(cols) to get colour of cube
  col<-ceiling(length(cols)*data$v[j])
  #Createa a voxel
  cubit = cube3d(color=col, alpha=0.3)
  #cubit$vb is a 4 by n matrix of vertices in homogeneous coordinates. Each column is a point.
  #Cube is originally 2x2x2. We shrink it to a 1x1x1 cube in the positive octant.
  cubit$vb[cubit$vb == -1] = 0
  cubit$vb[1,]      = cubit$vb[1,]+data$x[j] #Add x to first row
  cubit$vb[2,]      = cubit$vb[2,]+data$y[j] #Add y to second row
  cubit$vb[3,]      = cubit$vb[3,]+data$z[j] #Add z to third row
  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")