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

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

然后我随机分配一个集群到集合中:
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()    

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

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

最佳答案

您可以在第二次调用 geom_point 内即时计算每个集群的质心。 .这是一个使用 tidyverse 的示例职能。我们计算 Sepal.Length 的平均值和 Sepal.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()

enter image description here

关于r - 在ggplot2中添加一个簇的中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48976341/

相关文章:

python - 尽管改变 y 的值,.plot(y=) 仍给出相同的图表

r - ggplot2 将标签放在堆积条形图上

Mac 上的 R 错误 : "family ' Times New Roman' not included in postscript() device"

r - 为什么 geom_smooth 不绘图? (唯一值不足错误)

r - 如何在同一网格上自动绘制不同的曲线?

r - R中绘图的最佳拟合曲线

r - 在 R 中使用两个 data.frame 进行累积增长

r - 识别另一个列表中包含的列表元素,这些元素都是数据框的元素

r - 注释绘图边缘而不更改绘图限制或将 "expand"设置为 0

r - 如何在使用 R 中的 group_by 构建的散点图中使用不同回归模型的结果?