You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在factoextra的PCA双图中仅保留分组均值点并隐藏整体均值点

隐藏PCA双图中的整体均值点

使用factoextra包的fviz_pca_biplot()函数并设置mean.point=TRUE时,会同时显示各分组的均值点和整个数据集的钢蓝色整体均值点。要保留其他所有绘图元素、仅隐藏这个整体均值点,可通过以下两种方法实现:

方法一:手动添加分组均值点

不依赖mean.point=TRUE参数,自行计算各分组在PCA空间中的均值坐标,再手动添加到图中,这样就不会生成整体均值点:

library(tidyverse)
library(factoextra)
library(FactoMineR)

Groups <- as.factor(iris$Species)
res.pca <- prcomp(iris[-5], scale. = TRUE, center = TRUE)

# 绘制基础双图,不启用mean.point参数
p <- fviz_pca_biplot(res.pca,
                     pointsize=1,
                     habillage=Groups,
                     addEllipses = TRUE,
                     label = FALSE)

# 计算每个物种分组的原始数据均值,再转换为PCA坐标
mean_coords <- predict(res.pca, newdata = iris %>% 
                         group_by(Species) %>% 
                         summarise(across(everything(), mean))) %>%
  as.data.frame() %>%
  mutate(Species = levels(Groups))

# 将分组均值点添加到图中,可自定义大小和形状
p + geom_point(data = mean_coords, aes(x = PC1, y = PC2, color = Species), 
               size = 3, shape = 18)

方法二:修改已有绘图对象的图层

如果已经用mean.point=TRUE生成了包含整体均值点的图,可以直接修改ggplot对象的图层,移除对应整体均值点的图层(该图层是单独的geom_point,默认颜色为钢蓝色):

library(tidyverse)
library(factoextra)
library(FactoMineR)

Groups <- as.factor(iris$Species)
res.pca <- prcomp(iris[-5], scale. = TRUE, center = TRUE)

# 生成包含所有均值点的初始图
p <- fviz_pca_biplot(res.pca,
                     mean.point=TRUE,
                     pointsize=1,
                     habillage=Groups,
                     addEllipses = TRUE,
                     label = FALSE)

# 筛选并移除钢蓝色整体均值点对应的图层
p$layers <- p$layers[-which(sapply(p$layers, function(x) {
  !is.null(x$aes_params$color) && x$aes_params$color == "steelblue"
}))]

# 输出修改后的图
print(p)

内容的提问来源于stack exchange,提问作者Ginko-Mitten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:43:36