【问题标题】:ggplot K-Means Cluster Centers and Clustersggplot K-Means 聚类中心和聚类
【发布时间】:2016-05-29 18:26:23
【问题描述】:

我正在研究 K-Means 集群 ggplot(),几乎可以做我希望做的事情,但我只是不知道如何将我的中心着色为与它们各自集群相同的颜色。

到目前为止,我有这个:

data(mtcars)
library(ggplot2)
c1 <- kmeans(mtcars,9)
x <- tapply(mtcars$mpg,c1$cluster,mean)
y <- tapply(mtcars$hp,c1$cluster,mean)
kcenters <- data.frame(x,y)
ggplot(mtcars,aes(mpg,hp))+geom_point(col=c1$cluster,size=4) +  geom_point(data=kcenters,aes(x,y),pch=8,size=10)

这给了我这个情节:

所以我有两个问题,如何将我的中心着色为与它们所代表的集群相同?另外,我觉得xy 代码是多余的,不需要存在,因为在我的c1 值中,我可以看到带有位置矩阵的中心以及它们所代表的颜色。我只是无法弄清楚如何编写代码来访问这部分,因为每次尝试时都会收到诸如...之类的错误。

Error: Aesthetics must be either length 1 or the same as the data (9): shape, colour, size

另一个不太重要的问题是关于为什么我有两个不同的黑色集群。 R 不是有超过 8 种可以单独调用的独特颜色吗?

【问题讨论】:

    标签: r ggplot2 k-means


    【解决方案1】:

    你可以用

     ggplot(mtcars,aes(mpg,hp))+geom_point(col=c1$cluster,size=4) +  
         geom_point(data=kcenters,aes(x,y),pch=8,size=10,colour=1:9)
    

    要生成更多颜色,您应该查看rgb(...) http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/

    【讨论】:

      【解决方案2】:

      我建议您在使用 ggplot 之前将相关数据合并到 data.frames 中。然后您可以使用内置颜色选项。这是一个例子

      ggplot(cbind(mtcars, cluster=factor(c1$cluster)))+
          geom_point(aes(mpg,hp, col=cluster),size=4) +
          geom_point(data=cbind(kcenters, cluster=factor(1:nrow(kcenters))),aes(x,y, col=cluster),pch=8,size=10)
      

      这会产生

      【讨论】:

        猜你喜欢
        • 2015-06-04
        • 2020-02-21
        • 2015-04-11
        • 2019-03-16
        • 2011-08-13
        • 2013-08-08
        • 2013-02-14
        • 2018-01-14
        • 2016-01-01
        相关资源
        最近更新 更多