如何解决在 R 中的 K-means 中标记特定集群
如果我只想标记集群 3 中的数据点,需要对代码进行哪些修改?
> library(datasets)
head(iris)
library(ggplot2)
ggplot(iris,aes(Petal.Length,Petal.Width,color = Species)) + geom_point()
set.seed(20)
irisCluster <- kmeans(iris[,3:4],3,nstart = 20)
irisCluster
table(irisCluster$cluster,iris$Species)
setosa versicolor virginica
irisCluster$cluster <- as.factor(irisCluster$cluster)
ggplot(iris,color = irisCluster$cluster)) + geom_point()`
解决方法
您的问题有些模棱两可,但如果您想突出显示特定集群中的点,您可以使用 gghighlight 包,例如
library(datasets)
library(ggplot2)
#install.packages("gghighlight")
library(gghighlight)
set.seed(20)
irisCluster <- kmeans(iris[,3:4],3,nstart = 20)
irisCluster
table(irisCluster$cluster,iris$Species)
iris$cluster <- as.factor(irisCluster$cluster)
ggplot(iris,aes(Petal.Length,Petal.Width,color = factor(cluster))) +
geom_point() +
gghighlight(cluster == 3,keep_scales = TRUE)
,
您可以将不是 3 的 cluster
的标签设为空白。您可能需要根据您的实际数据调整标签的位置。
library(dplyr)
library(ggplot2)
iris %>%
mutate(cluster = irisCluster$cluster,label = replace(Petal.Length,cluster != 3,'')) %>%
ggplot() + aes(Petal.Length,color = cluster,label = label) +
geom_point() + geom_text(vjust = -0.5,hjust = -0.4)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。