如何在R语言散点图中添加聚类中心(质心)?
在散点图中添加质心的两种方法
基础R绘图(匹配你当前的代码)
你现在用的是基础R的plot和points函数,直接计算每组数据的x、y均值(也就是质心坐标),再用points标记出来就行,步骤如下:
- 分别计算AB组和BA组的质心坐标
- 用醒目的样式(比如实心圆、特殊颜色)把质心画在图上
完整代码示例:
# 绘制原始散点图 plot(Period_1_AB, Period_2_AB, pch = 0 , cex = .8) points(Period_1_BA, Period_2_BA, pch = 2, cex = .8) abline(0,1) # 计算AB组质心并绘制 ab_center <- c(mean(Period_1_AB), mean(Period_2_AB)) points(ab_center[1], ab_center[2], pch = 19, col = "red", cex = 1.2) # 计算BA组质心并绘制 ba_center <- c(mean(Period_1_BA), mean(Period_2_BA)) points(ba_center[1], ba_center[2], pch = 19, col = "blue", cex = 1.2)
ggplot2 方法(对应你提到的stat_summary)
如果用ggplot2绘图,stat_summary(fun = mean)确实是添加质心的便捷方式,前提是把数据整理成标准数据框格式:
library(ggplot2) # 把两组数据合并成一个数据框 df <- data.frame( x = c(Period_1_AB, Period_1_BA), y = c(Period_2_AB, Period_2_BA), group = rep(c("AB", "BA"), times = c(length(Period_1_AB), length(Period_1_BA))) ) # 绘图并自动添加质心 ggplot(df, aes(x = x, y = y, shape = group)) + geom_point(cex = 0.8) + geom_abline(slope = 1, intercept = 0) + # 用stat_summary添加质心,设置样式区分 stat_summary(fun = mean, geom = "point", shape = 19, size = 3, aes(color = group)) + theme_bw()
内容的提问来源于stack exchange,提问作者Jacob deril raj
相关产品推荐
相关产品推荐

