在ggplot2中添加集群的中心点

时间:2018-02-25 17:25:48

标签: r ggplot2

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

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

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

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

{{1}}

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

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

2 个答案:

答案 0 :(得分:3)

您可以在第二次调用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()

Rust docs

答案 1 :(得分:0)

在基数R(除ggplot2之外)我们可以这样做:

library(ggplot2)

iris$Cluster <- as.factor(rbinom(nrow(iris), 1, .5))  # more convenient

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, colour=Cluster)) +
  geom_point() +
  geom_point(aggregate(iris, by=list(Cluster=iris$Cluster), mean)[, 1:3], 
             size=10, shape=3) +
  theme_bw() + labs(x="Sepal Length", y="Sepal Width", color="Cluster Type")

收率:

enter image description here