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.
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)))
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With