r ggplot 在图上显示集群标签

r ggplot show cluster labels on the plot

我是 R 的新手,我正在尝试为我的聚类算法生成一系列图形。现在我正在使用以下代码:

ggplot(df,aes(x=V1,y=V2)) + 
geom_point(aes(colour = factor(cluster)),alpha=0.7) +
scale_colour_manual(values=c("purple", "green","orange","black")) +
ggtitle("Visualizing users and their K-Means Euclidean Clusters")

如您所见,我有四个集群,它们是 k-means 的结果。现在我想在我的情节上显示一些文字。例如下图中:

我需要在此图中显示在其上方的每个聚类(或任何文本,如聚类标签)的平均值(例如,绿色区域上方为 0.5)。我想我应该 geom_text 为此目的,但不幸的是我不知道该怎么做。非常感谢任何帮助。

谢谢

试试这个

library(ggplot2)
cl <- kmeans(iris[, 1:2], 3, nstart = 25)
ggplot(transform(iris[, 1:2], cl = factor(cl$cluster)), 
       aes(x = Sepal.Length, y = Sepal.Width, colour = cl)) +
  geom_point() + 
  scale_colour_manual(values=c("purple", "green","orange")) + 
  annotate("point", x = cl$centers[, 1], y = cl$centers[, 2], size = 5, colour = c("purple", "green","orange")) + 
  annotate("text", x = cl$centers[, 1], y = cl$centers[, 2], font = 2, size = 10,
           label = apply(cl$centers, 1, function(x) paste(sprintf('%02.2f', x), collapse = ",") ), 
           colour = c("purple", "green","orange") )