← 返回图册

BK37 · 带凸包与样本标签的 PCA 图

教程署名:用户本机案例(Codex 辅助编写);2026-11-03

原脚本已归档;论文作者代码未获得。论文及 GEO 数据遵循各自来源条款;不声明原论文代码许可。

图来源Nature Communications发表时间:2022-04-13

Sympathetic axonal sprouting induces changes in macrophage populations and protects against pancreatic cancer

案例说明与使用方法

# BK37 带凸包与样本标签的 PCA 图

参考 Guillot 等,Nature Communications (2022),doi:10.1038/s41467-022-29659-w,Fig. 4h 的图形样式。原图为胰腺组织 ROI 的形态学 PCA,并非 bulk RNA-seq。未获得论文作者完整绘图代码;归档的是本机 Codex 辅助生成的逐步 R 复现脚本,不能称为论文作者实现。

## 输入契约

scores:每行一个真实样本,必需 sample(唯一非空 ID)、label(显示标签)、group(真实分组)、PC1、PC2(有限数值)。保留其他元数据列。
variance:PC、variance_percent;PC1 与 PC2 各一行,其他主成分可保留。数值是相应 PCA 的解释方差百分数(0–100,不是 0–1 比例),总和不得超过 100;必须来自与 scores 相同的 PCA,不会从二维坐标猜测解释方差。
支持 CSV、TSV、XLSX,显式 column_map。支持 2–4 组,不自动分组、不重新聚类、不移动坐标。颜色/形状按 group_order(默认输入首次出现顺序)对应;默认青蓝圆点、橙红三角、金黄方块、紫色菱形。各组至少三个不共线点才能绘制凸包;否则只显示点与标签并返回提示。凸包是点的几何范围,不是置信区间。

## 实例与分析参数

固定示例为真实 GSE142279:20 对结直肠肿瘤/癌旁正常,40 个样本全部保留。NCBI 生成 TPM 按 GeneID 对齐 GRCh38.p13 注释,并用 GEO SOFT 的 tissue 字段核实样本。保留至少 10 个样本 TPM >=0.2 的基因,log2(TPM+1),按方差选前 2,000 基因,prcomp 样本为行、center=TRUE、scale.=FALSE。无患者效应校正,无离群值剔除。39,376 个基因中 21,563 个通过过滤;PC1=39.782230%,PC2=25.453520%。RC2_T(GSM4224326)保留。

绘图 MCP 只接受已有 PCA 结果,不重新执行以上分析。完整数据、分组、基因表、PCA 对象及简洁逐步分析脚本在 data/BK37/;从该目录执行 Rscript --vanilla run_analysis.R。原样归档脚本 code/user_supplied/BK37/Fig4h_TPM_PCA.R 中保留原工作路径;可运行副本仅修改 project_dir 为当前目录。

## 输出和样式

默认 8.4×6.8 英寸、300 dpi(2520×2040 像素),PDF/SVG/PNG;同色半透明凸包、样本标签、浅灰网格、右侧图例,真实解释方差,无标题/图注。输入与派生坐标、凸包顶点、解析后参数、字体和软件版本、来源、完整绘图入口 plot.R/rerun.R 一起保存。字号 font_size=11 是保持本例字号层级的基准倍率,图内基础文字为 15 pt。

先 get_method("BK37"),再 validate_inputs 和 render_plot;render_example("BK37") 运行真实 GEO 示例。不得为增强分离删除样本、按分组挑选基因或调整坐标。论文原图、原始截图与 GSE142279 示例在图册分别标注。

原始文件

以下文件按原始字节归档;MCP 适配代码另存,未覆盖作者代码。HTML 仅提供下载,不在此页执行。

Fig4h_TPM_PCA.R

下载原文件

SHA-256: dcedaf607110e905d6894f5adc971b4f23e3f50530821e8f5e31bff48a2eb376

# GSE142279:TPM PCA,参考 Nature Communications Fig. 4h 的绘图样式
# 从上到下逐段运行;如果项目搬家,只修改下一行。
project_dir <- "/Volumes/PortableSSD 1/002-biotrainee/04-绘图小技巧/F20240303-PCA图"

# 1. 加载包,准备文件路径
library(ggplot2)
library(ggrepel)
library(ragg)
set.seed(142279)

data_dir <- file.path(project_dir, "GSE142279_NCBI_generated")
work_dir <- file.path(project_dir, "Fig4h_GSE142279_R")
output_dir <- file.path(work_dir, "results")
dir.create(output_dir, showWarnings = FALSE)

tpm_file <- file.path(data_dir, "GSE142279_norm_counts_TPM_GRCh38.p13_NCBI.tsv.gz")
annotation_file <- file.path(data_dir, "Human.GRCh38.p13.annot.tsv.gz")
soft_file <- file.path(work_dir, "metadata", "GSE142279_family.soft.gz")

# 2. 读取 TPM 和基因注释
tpm_table <- read.delim(tpm_file, check.names = FALSE)
annotation <- read.delim(annotation_file, check.names = FALSE, quote = "", comment.char = "")
tpm <- as.matrix(tpm_table[, -1])
storage.mode(tpm) <- "double"
rownames(tpm) <- as.character(tpm_table$GeneID)
annotation$GeneID <- as.character(annotation$GeneID)
annotation <- annotation[match(rownames(tpm), annotation$GeneID), ]
stopifnot(identical(annotation$GeneID, rownames(tpm)), ncol(tpm) == 40)

# 3. 读取 GEO 元数据,按 GSM 对齐;每位患者有正常和肿瘤各一个样本
soft <- readLines(gzfile(soft_file), warn = FALSE)
sample_ids <- sub("^\\^SAMPLE = ", "", grep("^\\^SAMPLE = ", soft, value = TRUE))
sample_titles <- sub("^!Sample_title = ", "", grep("^!Sample_title = ", soft, value = TRUE))
tissues <- sub("^!Sample_characteristics_ch1 = tissue: ", "",
               grep("^!Sample_characteristics_ch1 = tissue: ", soft, value = TRUE))
all_samples <- data.frame(GSM = sample_ids, GEO_title = sample_titles, tissue = tissues)
all_samples$patient <- sub("_[NT]$", "", all_samples$GEO_title)
all_samples$group <- ifelse(all_samples$tissue == "tumor", "Colorectal tumor", "Adjacent normal")
all_samples$label <- all_samples$GEO_title
samples <- all_samples[match(colnames(tpm), all_samples$GSM), ]
samples$group <- factor(samples$group, levels = c("Adjacent normal", "Colorectal tumor"))
stopifnot(identical(samples$GSM, colnames(tpm)),
          identical(as.integer(table(samples$group)), c(20L, 20L)),
          all(table(samples$patient) == 2L))
write.csv(samples, file.path(output_dir, "sample_metadata.csv"), row.names = FALSE)
write.csv(all_samples[!all_samples$GSM %in% colnames(tpm), ],
          file.path(output_dir, "GEO_samples_absent_from_NCBI_matrix.csv"), row.names = FALSE)

# 4. TPM 过滤、转换,选方差最高的 2,000 个基因
samples_above_cutoff <- rowSums(tpm >= 0.2)
keep <- samples_above_cutoff >= 10
log_tpm <- log2(tpm[keep, ] + 1)
gene_variance <- apply(log_tpm, 1, var)
ranked_genes <- order(-gene_variance, rownames(log_tpm))
selected_ids <- rownames(log_tpm)[head(ranked_genes, 2000)]
pca_input <- t(log_tpm[selected_ids, ])

filter_table <- data.frame(GeneID = rownames(tpm), Symbol = annotation$Symbol,
                           samples_TPM_ge_0.2 = samples_above_cutoff,
                           passes_expression_filter = keep,
                           selected_for_PCA = rownames(tpm) %in% selected_ids)
write.csv(filter_table, file.path(output_dir, "gene_filter_summary.csv"), row.names = FALSE)
selected_genes <- annotation[match(selected_ids, annotation$GeneID), ]
selected_genes$variance_log2_TPM_plus_1 <- gene_variance[selected_ids]
selected_genes$variance_rank <- seq_along(selected_ids)
write.csv(selected_genes, file.path(output_dir, "selected_genes.csv"), row.names = FALSE)

# 5. PCA:样本为行,基因为列;中心化,不按基因标准差缩放
pca <- prcomp(pca_input, center = TRUE, scale. = FALSE)
variance_fraction <- pca$sdev^2 / sum(pca$sdev^2)
explained <- data.frame(PC = paste0("PC", seq_along(variance_fraction)),
                        variance_fraction = variance_fraction,
                        variance_percent = 100 * variance_fraction,
                        cumulative_percent = 100 * cumsum(variance_fraction))
scores <- cbind(samples, as.data.frame(pca$x))
write.csv(scores, file.path(output_dir, "PCA_sample_scores.csv"), row.names = FALSE)
write.csv(explained, file.path(output_dir, "PCA_explained_variance.csv"), row.names = FALSE)
write.csv(data.frame(GeneID = rownames(pca$rotation), pca$rotation, check.names = FALSE),
          file.path(output_dir, "PCA_gene_loadings.csv"), row.names = FALSE)
saveRDS(pca, file.path(output_dir, "PCA_object.rds"))
saveRDS(list(input = pca_input, metadata = samples,
             parameters = list(tpm_cutoff = 0.2, min_samples = 10, top_n = 2000,
                               transform = "log2(TPM + 1)", center = TRUE,
                               scale = FALSE, patient_correction = FALSE)),
        file.path(output_dir, "PCA_inputs_and_parameters.rds"))

# 6. 绘图:组内凸包、样本标签、原始 PC 坐标
hull_normal <- scores[scores$group == "Adjacent normal", ]
hull_normal <- hull_normal[chull(hull_normal$PC1, hull_normal$PC2), ]
hull_tumor <- scores[scores$group == "Colorectal tumor", ]
hull_tumor <- hull_tumor[chull(hull_tumor$PC1, hull_tumor$PC2), ]
hulls <- rbind(hull_normal, hull_tumor)
colors <- c("Adjacent normal" = "#49BCCB", "Colorectal tumor" = "#FF7950")
shapes <- c("Adjacent normal" = 16, "Colorectal tumor" = 17)

figure <- ggplot(scores, aes(PC1, PC2, color = group)) +
  geom_polygon(data = hulls, aes(fill = group, group = group),
               alpha = 0.14, linewidth = 0.85, show.legend = FALSE) +
  geom_point(aes(shape = group), size = 3.1, alpha = 0.85) +
  geom_text_repel(aes(label = label), size = 3, seed = 142279,
                  box.padding = 0.4, point.padding = 0.22,
                  min.segment.length = 0, segment.alpha = 0.45,
                  segment.size = 0.25, max.overlaps = Inf,
                  max.iter = 100000, max.time = Inf, show.legend = FALSE) +
  scale_color_manual(values = colors, name = NULL) +
  scale_fill_manual(values = colors, name = NULL) +
  scale_shape_manual(values = shapes, name = NULL) +
  scale_x_continuous(expand = expansion(mult = 0.14)) +
  scale_y_continuous(expand = expansion(mult = 0.14)) +
  labs(x = sprintf("Dim1 (%.1f%%)", explained$variance_percent[1]),
       y = sprintf("Dim2 (%.1f%%)", explained$variance_percent[2])) +
  coord_cartesian(clip = "off") +
  theme_bw(base_size = 15, base_family = "sans") +
  theme(aspect.ratio = 1, panel.border = element_blank(),
        panel.grid.major = element_line(color = "#E8E8E8", linewidth = 0.6),
        panel.grid.minor = element_line(color = "#F0F0F0", linewidth = 0.35),
        axis.ticks = element_blank(), axis.text = element_text(color = "#555555"),
        axis.title = element_text(color = "#555555"),
        legend.position = "right", legend.text = element_text(size = 12),
        legend.key = element_rect(fill = "white", color = NA),
        legend.key.height = grid::unit(0.8, "cm"),
        plot.margin = margin(18, 18, 18, 18)) +
  guides(color = guide_legend(override.aes = list(size = 4, alpha = 1)))

ggsave(file.path(output_dir, "Fig4h_TPM_PCA.png"), figure,
       width = 8.4, height = 6.8, units = "in", dpi = 300,
       device = ragg::agg_png, bg = "white")
ggsave(file.path(output_dir, "Fig4h_TPM_PCA.pdf"), figure,
       width = 8.4, height = 6.8, units = "in", device = cairo_pdf, bg = "white")

# 7. 保存运行记录
writeLines(c(paste("Input genes:", nrow(tpm)), paste("Samples:", ncol(tpm)),
             paste("Genes passing TPM filter:", sum(keep)),
             paste("Selected genes:", length(selected_ids)),
             sprintf("PC1: %.6f%%; PC2: %.6f%%",
                     explained$variance_percent[1], explained$variance_percent[2])),
           file.path(output_dir, "analysis_summary.txt"))
writeLines(capture.output(sessionInfo()), file.path(output_dir, "sessionInfo.txt"))
checksums <- tools::md5sum(c(tpm_file, annotation_file, soft_file))
write.csv(data.frame(file = names(checksums), md5 = unname(checksums)),
          file.path(output_dir, "input_checksums.csv"), row.names = FALSE)