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)
这给了我这个情节:
所以我有两个问题,我如何才能将我的中心着色为与它们所代表的集群相同的颜色?另外,我觉得 x
和 y
代码好像是额外的,不需要在那里,因为在我的 c1
值中我可以看到带有位置矩阵和颜色的中心他们也代表。我只是一直无法弄清楚如何编写代码来访问这部分,因为每次我尝试都会收到诸如...
之类的错误
Error: Aesthetics must be either length 1 or the same as the data (9): shape, colour, size
另一个不太重要的问题是关于为什么我有两个不同的黑色簇。 R 不是有 8 种以上的独特颜色可以自行调用吗?
您可以使用
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)/
我建议您在使用 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)
这会产生
我正在研究 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)
这给了我这个情节:
所以我有两个问题,我如何才能将我的中心着色为与它们所代表的集群相同的颜色?另外,我觉得 x
和 y
代码好像是额外的,不需要在那里,因为在我的 c1
值中我可以看到带有位置矩阵和颜色的中心他们也代表。我只是一直无法弄清楚如何编写代码来访问这部分,因为每次我尝试都会收到诸如...
Error: Aesthetics must be either length 1 or the same as the data (9): shape, colour, size
另一个不太重要的问题是关于为什么我有两个不同的黑色簇。 R 不是有 8 种以上的独特颜色可以自行调用吗?
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)/
我建议您在使用 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)
这会产生