在ggplot2中添加一个簇的中心点

Hen*_*ten 4 r ggplot2

出于训练目的,我想创建一个 Shiny 应用程序,概述 KNN 算法中的步骤。我想要显示的第一步是两个集群的中心。

我使用 ggplot 首先显示 iris 数据集的 Sepal.Length 和 Sepal.Width。

library(ggplot2)

g <- ggplot(data=iris, aes(x=iris$Sepal.Length, y = iris$Sepal.Width))
g + geom_point()          
Run Code Online (Sandbox Code Playgroud)

然后我随机分配一个集群到集合中:

iris$Cluster <- 0
for(i in 1:nrow(iris)){
  randInt <- x1 <- round(runif(1, 0, 1),0)
  ifelse(randInt == 0,iris$Cluster[i] <- 1, iris$Cluster[i] <- 0)
}
iris$Cluster <- as.factor(iris$Cluster)                               
g <- ggplot(data=iris, aes(x=iris$Sepal.Length, y = iris$Sepal.Width, colour = Cluster))
g + geom_point()    
Run Code Online (Sandbox Code Playgroud)

现在我想采取的下一步是在我的图中显示一个点,它是集群 0 和集群 1 的中心。

关于如何在 ggplot2 中执行此操作的任何想法

eip*_*i10 5

您可以在第二次调用 时动态计算每个簇的质心geom_point。这是一个使用tidyverse函数的例子。我们计算每个集群的平均值Sepal.LengthSepal.Width内部,并使用十字作为点标记绘制这些平均值。另请注意,您不应在 中重述数据框名称aes,而应单独使用列名称。

library(tidyverse)

# Assign random cluster value
iris$cluster = sample(0:1, nrow(iris), replace=TRUE)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, colour=factor(cluster))) +
  geom_point() +
  geom_point(data=iris %>% 
               group_by(cluster) %>% 
               summarise_at(vars(matches("Sepal")), mean),
             size=5, shape=3) +
  theme_classic()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明