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

如何使用ggplot绘制经Hellinger变换的PCA分析结果图?

报错原因

ggfortify的autoplot()仅适配了stats包的prcomp/princomp等基础PCA对象,未适配vegan包生成的rda/cca类排序对象,因此直接调用会返回不支持的错误。

方案1:直接对Hellinger变换后的数据做prcomp(最简便)

Hellinger只是数据预处理方法,变换后的数据可以直接用prcomp做PCA,完全兼容原有的autoplot逻辑,载荷、置信椭圆等功能都可以直接通过参数控制:

library(ggfortify)
library(vegan)
df <- iris[1:4]
# Hellinger变换
df.hell <- decostand(df, method = "hellinger")
# 对变换后的数据做PCA,无需用rda
# 注意:Hellinger变换后通常不需要再做标准化,scale.参数按需调整
pca_hell <- prcomp(df.hell, scale. = FALSE)

# 原有autoplot代码可直接使用
autoplot(pca_hell, data = iris, colour = 'Species',
         loadings = TRUE, loadings.colour = 'blue',
         loadings.label = TRUE, loadings.label.size = 3,
         frame = TRUE, frame.type = 'norm') # 加frame参数即可绘制置信椭圆
方案2:基于vegan的rda结果手动提取元素绘图

如果你需要保留vegan的rda分析结果,可以手动提取样本得分、载荷、解释率等元素,直接用ggplot叠加图层实现所有绘图需求:

第一步:提取绘图所需数据

library(ggplot2)
library(vegan)
df <- iris[1:4]
df.hell <- decostand(df, method = "hellinger")
rda_hell <- rda(df.hell)

# 提取样本得分,合并分组信息
site_scores <- as.data.frame(scores(rda_hell, display = "sites"))
site_scores <- cbind(site_scores, Species = iris$Species)

# 提取变量载荷
loadings <- as.data.frame(scores(rda_hell, display = "species"))
loadings$varname <- rownames(loadings)

# 提取排序轴解释率,用于轴标签
axis_expl <- round(rda_hell$CA$eig / sum(rda_hell$CA$eig) * 100, 2)

第二步:组合图层绘图

ggplot() +
  # 样本散点
  geom_point(data = site_scores, aes(x = PC1, y = PC2, color = Species), size = 2) +
  # 95%置信椭圆
  stat_ellipse(data = site_scores, aes(x = PC1, y = PC2, color = Species), level = 0.95) +
  # 载荷箭头
  geom_segment(data = loadings, aes(x = 0, y = 0, xend = PC1, yend = PC2), 
               arrow = arrow(length = unit(0.2, "cm")), color = "blue") +
  # 载荷标签
  geom_text(data = loadings, aes(x = PC1, y = PC2, label = varname), 
            color = "blue", size = 3, vjust = 1.2) +
  # 轴标签添加解释率
  labs(x = paste0("PC1 (", axis_expl[1], "%)"),
       y = paste0("PC2 (", axis_expl[2], "%)")) +
  theme_bw()
补充说明
  • 如果载荷箭头过小和样本点重叠,可以给xend/yend乘以缩放系数(比如xend = PC1 * 2),调整到合适的显示比例即可
  • 若需要填充式置信椭圆,可改为stat_ellipse(geom = "polygon", aes(fill = Species), alpha = 0.2)
  • 如需添加分组重心、分组标签等元素,可先对site_scores按分组聚合计算均值后再叠加对应图层

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 20:24:03