gpt4 book ai didi

r ggplot 在图上显示集群标签

转载 作者:行者123 更新时间:2023-12-05 06:44:01 27 4
gpt4 key购买 nike

我是 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 的结果。现在我想在我的情节上显示一些文字。例如在下图中:

enter image description here

我需要在此图中显示在其上方的每个集群(或集群标签之类的任何文本)的平均值(例如,绿色区域上方为 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") )

enter image description here

关于r ggplot 在图上显示集群标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31173278/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com