BioF3 FigCode · SCI 绘图代码集
批次 PCA(Batch Effect PCA)
分类:降维可视化 | 依赖包:ggplot2、patchwork
解决的生物学问题
批次效应是否被成功去除?校正后样本是否按生物学分组而非批次聚类?
应用场景
- ComBat-seq 批次校正效果验证
- limma removeBatchEffect 评估
- 多中心数据整合质控
- 校正前后对比展示
输入数据格式
校正前后的表达矩阵 + 批次和分组注释
关键参数
- batch 批次变量
- mod 保护的生物学变量
- method 校正方法(ComBat / limma)
- par.prior 是否参数化先验
- ntop PCA 使用基因数
快速开始
1. 直接在线运行
打开 FigCode 在线绘图,点击本工具卡片的"在线绘图"按钮即可用内置示例数据出图,零环境配置。
2. 本地复现
下载脚本和示例数据,本地 RStudio 运行:
# 下载
curl -O https://<your-site>/figcode/scripts/combat-pca.R
curl -O https://<your-site>/figcode/data/combat-pca.csv
3. 安装依赖
# CRAN 包
install.packages(c("ggplot2", "patchwork"))
# Bioconductor 包(如需)
# BiocManager::install(c())
完整代码
library(ggplot2)
library(patchwork)
# --- Demo: simulate batch effect before/after ---
set.seed(42)
n <- 12
batch <- rep(c("Batch1", "Batch2"), each = 6)
condition <- rep(c("Treatment", "Control"), times = 6)
# Before: samples cluster by batch
pc1_before <- c(rnorm(6, -5, 1.5), rnorm(6, 5, 1.5))
pc2_before <- rnorm(n, 0, 2)
# After: samples cluster by condition
pc1_after <- ifelse(condition == "Treatment", rnorm(n, 5, 1.5), rnorm(n, -5, 1.5))
pc2_after <- rnorm(n, 0, 2)
df_before <- data.frame(PC1=pc1_before, PC2=pc2_before, Batch=batch, Condition=condition)
df_after <- data.frame(PC1=pc1_after, PC2=pc2_after, Batch=batch, Condition=condition)
# --- Plot ---
p1 <- ggplot(df_before, aes(PC1, PC2, color=Batch, shape=Condition)) +
geom_point(size=4) + ggtitle("Before Correction") +
theme_classic() + theme(legend.position="bottom")
p2 <- ggplot(df_after, aes(PC1, PC2, color=Condition, shape=Batch)) +
geom_point(size=4) + ggtitle("After Correction") +
scale_color_manual(values=c(Treatment="#dc2626", Control="#2563eb")) +
theme_classic() + theme(legend.position="bottom")
p1 + p2
替换为自己的数据
脚本中以 # --- Demo data --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:
- 输入格式:校正前后的表达矩阵 + 批次和分组注释
- 使用
read.csv()/readRDS()读取本地文件
延伸阅读
- 相关教程:批次 PCA 完整流程
- 出现 bug?欢迎在 FigCode 页面 点击对应卡片,在评论区留言。