簡體   English   中英

ggplot K-Means群集中心和群集

[英]ggplot K-Means Cluster Centers and Clusters

我正在研究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種獨特的顏色?

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

這產生

在此處輸入圖片說明

在此處輸入圖片說明 您可以使用

 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_ rgb(...) /

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM