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

如何在R Studio中用条形图可视化PCA的PC1与PC2变量载荷?

用tidyverse可视化PCA的PC1和PC2载荷

以下是直接可用的代码方案,帮你快速可视化载荷并识别绝对值大于0.3的变量:

1. 加载依赖包

library(tidyverse)

2. 整理PCA载荷数据

先把PCA模型的载荷矩阵转换成tidy格式,方便后续可视化:

# 处理载荷数据,保留PC1、PC2并转为长格式
loadings_tidy <- as_tibble(pca$rotation, rownames = "variable") %>%
  select(variable, PC1, PC2) %>%
  pivot_longer(cols = c(PC1, PC2), names_to = "component", values_to = "loading") %>%
  # 标记绝对值大于0.3的载荷
  mutate(is_high = abs(loading) > 0.3)

3. 绘制分面条形图

用分面同时展示PC1和PC2的载荷,红色虚线标记±0.3阈值:

ggplot(loadings_tidy, aes(x = variable, y = loading, fill = is_high)) +
  geom_col() +
  facet_wrap(~component, ncol = 2) +
  # 添加阈值参考线
  geom_hline(yintercept = c(-0.3, 0.3), linetype = "dashed", color = "red") +
  # 旋转x轴标签避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "PC1 & PC2 载荷可视化", x = "原始变量", y = "载荷值") +
  scale_fill_manual(values = c("FALSE" = "gray80", "TRUE" = "steelblue"))

4. 可选:按载荷排序的单成分可视化

如果想更清晰地看单个主成分的载荷排序,可以用以下代码:

# 单独展示PC1,变量按载荷值排序
loadings_tidy %>%
  filter(component == "PC1") %>%
  ggplot(aes(x = reorder(variable, loading), y = loading, fill = is_high)) +
  geom_col() +
  geom_hline(yintercept = c(-0.3, 0.3), linetype = "dashed", color = "red") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(title = "PC1 载荷排序可视化", x = "原始变量", y = "载荷值")

说明

  • 转换为长格式是为了利用ggplot2的分面功能,同时对比两个主成分的载荷分布
  • is_high列用来给绝对值大于0.3的载荷添加颜色高亮,一眼就能识别目标变量
  • 旋转x轴标签是为了避免变量名较长时出现重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 12:54:57