ggplot K-Means集群中心和集群

时间:2016-02-17 20:28:18

标签: r ggplot2 k-means

我正在研究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)

这给了我这个情节:enter image description here

所以我有两个问题,我如何为我们的中心着色与他们所代表的群集相同?此外,我觉得xy代码是额外的,不需要在那里,因为在我的c1值中,我可以看到具有位置矩阵的中心和它们代表的颜色。我还没有能够弄清楚如何编写代码来访问这个部分,因为每次我尝试时都会出现错误,例如......

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

另一个不那么重要的问题是为什么我有两个不同的黑色星团。 R不仅有8种以上的独特颜色吗?

2 个答案:

答案 0 :(得分:3)

我建议您在使用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)

这会产生

enter image description here

答案 1 :(得分:1)

enter image description here您可以使用

 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)/