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

如何在R语言PCA可视化中为椭圆添加标签?

给PCA椭圆添加标签的解决方案

factoextra包的fviz_pca_biplot函数本身没有直接添加椭圆标签的参数,你可以通过以下两种方式实现需求:

方法一:手动标注(适合类别较少的场景)

先绘制基础PCA双图,再用ggplot2的annotate函数手动指定标签位置:

data(iris)
res.pca <- prcomp(iris[, -5],  scale = TRUE)

# 绘制基础PCA图
p <- fviz_pca_biplot(res.pca, label = "var", habillage=iris$Species,
                addEllipses=TRUE, ellipse.level=0.95,
                ggtheme = theme_minimal())

# 添加椭圆标签
p + annotate("text", x = -2, y = 2.5, label = "Setosa", fontface = "bold", size = 5) +
  annotate("text", x = 0, y = -1, label = "Versicolor", fontface = "bold", size = 5) +
  annotate("text", x = 2, y = 0.5, label = "Virginica", fontface = "bold", size = 5)

注:x和y参数需根据图中椭圆实际位置调整,确保标签处于醒目位置。

方法二:自动提取椭圆中心添加标签(通用场景)

通过计算每个类别PCA得分的均值(即椭圆中心坐标),自动添加标签,无需手动定位:

data(iris)
res.pca <- prcomp(iris[, -5],  scale = TRUE)
library(dplyr)

# 提取PCA得分,按物种分组计算PC1/PC2的均值(椭圆中心)
score_means <- as.data.frame(res.pca$x) %>%
  mutate(Species = iris$Species) %>%
  group_by(Species) %>%
  summarise(PC1 = mean(PC1), PC2 = mean(PC2))

# 绘制PCA图并自动添加标签
fviz_pca_biplot(res.pca, label = "var", habillage=iris$Species,
                addEllipses=TRUE, ellipse.level=0.95,
                ggtheme = theme_minimal()) +
  geom_text(data = score_means, aes(x = PC1, y = PC2, label = Species),
            fontface = "bold", size = 5, vjust = -1)

vjust = -1让标签位于椭圆中心上方,可根据需求调整vjust或hjust改变标签位置。

内容的提问来源于stack exchange,提问作者Darwin PC

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:45:38