R 3d plot with categorical colors

I have 4 columns of data in R that looks like

x   y   z  group

      

the columns group

have categorical values, so they are a discrete set of values, while the other three columns are contiguous.

I want to make a 3D plot in R with x

, y

and z

, and point color with group. I also want to have a legend on this plot. How can i do this? I have no particular preference for real colors. I believe I rainbow(length(unique(group))

should do well.

+3


source to share


1 answer


Here is an example using scatterplot3d

and based on the example in vignetics

library(scatterplot3d)

# some basic dummy data
DF <- data.frame(x = runif(10),
  y = runif(10), 
  z = runif(10), 
  group = sample(letters[1:3],10, replace = TRUE))

# create the plot, you can be more adventurous with colour if you wish
s3d <- with(DF, scatterplot3d(x, y, z, color = as.numeric(group), pch = 19))

# add the legend using `xyz.convert` to locate it 
# juggle the coordinates to get something that works.
legend(s3d$xyz.convert(0.5, 0.7, 0.5), pch = 19, yjust=0,
       legend = levels(DF$group), col = seq_along(levels(DF$group)))

      

enter image description here



Or you can use lattice

and cloud

, in which case you can build the key usingkey

cloud(z~x+y, data = DF, pch= 19, col.point = DF$group, 
  key = list(points = list(pch = 19, col = seq_along(levels(DF$group))), 
  text = list(levels(DF$group)), space = 'top', columns = nlevels(DF$group)))

      

enter image description here

+7


source







All Articles