4

I have 4 columns of data in R that looks like this

x   y   z  group

the group columns has categorical values, so it is a discrete set of values, whereas the other three columns are continuous.

I want to make a 3d plot in R with x, y, and z, and where the color of the dot is given by "group". I also want to have a legend to this plot. How can I do this? I don't have a particular preference on the actual colors. I suppose rainbow(length(unique(group)) should do fine.

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

1 Answers1

10

Here is an example using scatterplot3d and based on the example in the vignette

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 could use lattice and cloud, in which case you can construct the key using key

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

mnel
  • 113,303
  • 27
  • 265
  • 254
  • 1
    Any idea how to make a version that's rotatable such as what plot3d makes? – CodeGuy Feb 05 '13 at 04:28
  • use `rgl`. I'll try and add an example – mnel Feb 05 '13 at 04:29
  • Awesome, looking forward to it – CodeGuy Feb 05 '13 at 04:30
  • CodeGuy, how did you manage to sort out the colours for each of the dots? I have a sequence of values between 0.0 and 1.2 for which I would like to assign colours for use in the 3D plot. So, 0.0-0.19 = Red, 0.2-0.39 = Blue and so forth.... Any help is appreciated! – stars83clouds Oct 02 '13 at 00:43
  • using `as.numeric()` on `group` results in NAs and a warning from R that `NAs introduced by coercion`. – Yu Chen Aug 19 '17 at 19:45