【问题标题】:How can I make a 3D plot in R of the clusters obtained with kmeans?如何在 R 中绘制使用 kmeans 获得的集群的 3D 图?
【发布时间】:2020-06-20 16:50:27
【问题描述】:

我的 包含具有 3 个属性的观察,我使用 将它们分为四个不同的组。我的目标是在 图中绘制我获得的集群,以便快速轻松地查看集群数据。

但是我不知道如何在 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 绘图?提前致谢!

【问题讨论】:

  • 能否请您提供数据框bella 或者如果它太大,那么dput(bella)?发布您的数据或没有数据的图像会使我们难以为您提供帮助!

标签: dataframe k-means 3d r ggplot2 3d cluster-analysis k-means


【解决方案1】:

您没有提供您的数据,因此我将使用内置的虹膜数据进行说明。

这里有两种方法:

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

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

运行此版本时,您可以单击图像并旋转它以查看不同的角度。

【讨论】:

    【解决方案2】:

    你也可以用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)
    

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 2019-09-14
      • 2014-06-24
      • 2021-08-01
      • 2019-04-04
      • 2016-11-09
      • 2013-12-23
      • 2013-04-26
      • 1970-01-01
      相关资源
      最近更新 更多