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

R语言中如何使用ggplot在PCA图上标注特定数据点

PCA图参考

tidyverse环境下PCA图标记特定ID点的实现方案

前提:你需要先把PCA计算后的坐标、样本ID整合为标准数据框,核心字段包含样本ID列(示例中列名为sample_id)、PC1、PC2,按以下步骤操作即可:

  • 定义待标记的目标ID集合
    把你需要定位的5个ID替换到向量中即可:
    # 替换为你实际要找的5个目标ID
    target_id_list <- c("ID1", "ID2", "ID3", "ID4", "ID5")
    
  • 给绘图数据打分类标记
    基于已有的PCA结果数据框(示例中对象名为pca_df)新增字段区分目标点和普通点:
    pca_plot_df <- pca_df %>%
      mutate(is_target = sample_id %in% target_id_list)
    
  • 绘图并高亮目标点
    搭配ggrepel包实现标签自动避障,避免文字和点位重叠,普通点设为低透明度灰色突出目标点:
    # 未安装ggrepel先执行安装:install.packages("ggrepel")
    library(ggrepel)
    
    ggplot(pca_plot_df, aes(x = PC1, y = PC2)) +
      # 先绘制所有非目标普通点
      geom_point(
        data = . %>% filter(!is_target),
        color = "gray60",
        alpha = 0.5,
        size = 1.5
      ) +
      # 高亮绘制目标点
      geom_point(
        data = . %>% filter(is_target),
        color = "#c82423",
        size = 3
      ) +
      # 仅为目标点添加ID标签,自动调整位置避免重叠
      geom_text_repel(
        data = . %>% filter(is_target),
        aes(label = sample_id),
        size = 3.5,
        box.padding = 0.6,
        max.overlaps = 15
      ) +
      labs(x = "PC1", y = "PC2") +
      theme_minimal()
    

如果你是直接用prcomp()生成的PCA结果,还没提取坐标,可以先用下面的代码整理成可用的绘图数据框,再执行上述步骤:

# pca_calc 替换为你prcomp函数生成的结果对象
pca_df <- as.data.frame(pca_calc$x[, 1:2]) %>%
  rownames_to_column("sample_id")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:15:51