出于训练目的,我想创建一个 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()
关于r - 在ggplot2中添加一个簇的中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48976341/