如何在 R 中绘制用 kmeans 获得的簇的 3D 图?

How can I make a 3D plot in R of the clusters obtained with kmeans?

我的 contains observations with 3 attributes, I have used to cluster them into four different groups. My goal is to plot the clusters I have obtained in a 图是为了快速简便地查看聚类数据。

但是我不知道如何在 3D 中绘图,我有适用于 2D 的代码,但我不知道如何调整它以添加维度。 我的代码如下:

    library(ggplot2)
set.seed(137)
km = kmeans(bella,4, nstart=25)

df = as.data.frame(bella)
df$cluster = factor(km$cluster)
centers=as.data.frame(km$centers)
df

 ggplot(data=df, aes(x=Annual.Income..k.., z = Age, y=Spending.Score..1.100.)) +
 geom_point() + theme(legend.position="right") +
 geom_point(data=centers,
 aes(x=Annual.Income..k.., y=Spending.Score..1.100., z=Age,color=as.factor(c(1:4))), aes(x=Age, y=Spending.Score..1.100., color=as.factor(c(1:4))),
 size=10, alpha=.3, show.legend=FALSE)

如何创建 3D 绘图?提前致谢!

你不提供你的数据,所以我将用内置的虹膜数据来说明。

这里有两种方式:

library(scatterplot3d)
scatterplot3d(iris[,2:4], pch=20, color=rainbow(3)[km$cluster])

library(rgl)
plot3d(iris[,2:4], col=rainbow(3)[km$cluster])

当你运行这个版本时,你可以点击图片并旋转它来查看不同的角度。

你也可以使用 plotly:

df = iris[,1:3]
df$cluster = factor(kmeans(df,3)$cluster)

library(plotly)
library(dplyr)
p <- plot_ly(df, x=~Sepal.Length, y=~Sepal.Width, 
z=~Petal.Length, color=~cluster) %>%
     add_markers(size=1.5)
print(p)

htmlwidget 的另一个选项是使用 threejs(它基于 scatterplot3d,如@G5W 的回答所示):

library(threejs)
COLS = RColorBrewer::brewer.pal(3,"Set2")
scatterplot3js(as.matrix(df[,1:3]),col=COLS[df$cluster],size=0.3)