我在R中有4列数据,看起来像这样
x y z group
group
列具有分类值,因此它是一组离散值,而其他三列是连续的。
我想在R中使用x
,y
和z
创建一个3d图,其中点的颜色由“group”给出。我也希望有一个这个情节的传奇。我怎样才能做到这一点?我对实际颜色没有特别的偏好。我认为rainbow(length(unique(group))
应该没问题。
答案 0 :(得分:7)
以下是使用scatterplot3d
并基于小插图
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)))
或者,您可以使用lattice
和cloud
,在这种情况下,您可以使用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)))