[英]How can I make a 3D plot in R of the clusters obtained with kmeans?
My dataframe contains observations with 3 attributes, I have used k-means to cluster them into four different groups.我的数据框包含具有 3 个属性的观察结果,我使用k-means将它们分为四个不同的组。 My goal is to plot the clusters I have obtained in a 3d plot in order to have a quick and easy way to look at the clustered data.
我的目标是绘制我在3d图中获得的集群,以便快速轻松地查看集群数据。
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])
OR或者
library(rgl)
plot3d(iris[,2:4], col=rainbow(3)[km$cluster])
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.