简体   繁体   English

如何在用 kmeans 获得的集群的 R 中制作 3D 图?

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

My contains observations with 3 attributes, I have used to cluster them into four different groups.我的包含具有 3 个属性的观察结果,我使用将它们分为四个不同的组。 My goal is to plot the clusters I have obtained in a plot in order to have a quick and easy way to look at the clustered data.我的目标是绘制我在图中获得的集群,以便快速轻松地查看集群数据。

However I do not know how to plot in 3D, I have code that works with 2D but I don't know how to adapt it to add a dimension.但是我不知道如何在 3D 中绘图,我有使用 2D 的代码,但我不知道如何调整它以添加维度。 The code I have is the following:我的代码如下:

    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)

How can I create a 3D plot?如何创建 3D 绘图? Thanks in advance!提前致谢!

You do not provide your data so I will illustrate with the built-in iris data.你不提供你的数据,所以我将用内置的虹膜数据来说明。

Here are two ways:这里有两种方法:

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

scatterplot3d 的结果

OR或者

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

来自 rgl 的 3D 绘图

When you run this version, you can click on the image and rotate it around to see different angles.当您运行此版本时,您可以单击图像并将其旋转以查看不同的角度。

You can also use plotly:您还可以使用 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)

在此处输入图片说明

Another option with htmlwidget is using threejs (which is based on scatterplot3d as shown in @G5W's answer): 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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM