BioF3 FigCode · SCI 绘图代码集

拷贝数热图(CNV Heatmap)

导出日期:2026年6月27日

分类:基因组 | 依赖包:ComplexHeatmap、circlize

解决的生物学问题

我的队列中哪些染色体区段反复发生扩增/缺失?这些区段上有什么驱动基因?

应用场景

输入数据格式

矩阵:行 = 基因组 bin(按染色体排序),列 = 样本,值 = log2 copy ratio

关键参数

快速开始

1. 直接在线运行

打开 FigCode 在线绘图,点击本工具卡片的"在线绘图"按钮即可用内置示例数据出图,零环境配置。

2. 本地复现

下载脚本和示例数据,本地 RStudio 运行:

# 下载
curl -O https://<your-site>/figcode/scripts/cnv-heatmap.R
curl -O https://<your-site>/figcode/data/cnv-heatmap.csv

3. 安装依赖

# CRAN 包
install.packages(c("ComplexHeatmap", "circlize"))

# Bioconductor 包(如需)
# BiocManager::install(c())

完整代码

library(ComplexHeatmap)
library(circlize)

# --- Demo: 1000 bins × 30 samples ---
set.seed(42)
n_bins <- 1000
n_samp <- 30

# Spread bins across chromosomes proportional to size
chr_lens <- c(250,243,198,191,181,171,159,146,141,135,135,134,
              115,108,102,90,81,78,59,63,48,51)
chr_lens <- round(n_bins * chr_lens / sum(chr_lens))
chr_lens[1] <- chr_lens[1] + (n_bins - sum(chr_lens))   # rounding fix
chr <- rep(paste0("chr", 1:22), times = chr_lens)

# CNV matrix (mostly near 0, with some focal events)
cnv <- matrix(rnorm(n_bins * n_samp, 0, 0.3), nrow = n_bins)
# Inject amplification on chr8q (around bin 370-400)
cnv[370:400, 1:10] <- cnv[370:400, 1:10] + 2
# Inject deletion on chr17 (around bin 600-630)
cnv[600:630, 11:20] <- cnv[600:630, 11:20] - 1.8

rownames(cnv) <- paste0(chr, "_", ave(seq_along(chr), chr, FUN = seq_along))
colnames(cnv) <- paste0("S", 1:n_samp)

# --- Heatmap ---
col_fun <- colorRamp2(c(-2, 0, 2), c("#2563eb", "white", "#dc2626"))

Heatmap(
  t(cnv),                            # rows = samples, cols = bins
  name = "log2 ratio",
  col = col_fun,
  cluster_rows = TRUE,
  cluster_columns = FALSE,
  show_column_names = FALSE,
  show_row_names = FALSE,
  column_split = factor(chr, levels = paste0("chr", 1:22)),
  column_gap = grid::unit(0.5, "mm"),
  column_title_gp = grid::gpar(fontsize = 7),
  row_title = "Samples",
  heatmap_legend_param = list(title = "log2 CR")
)

替换为自己的数据

脚本中以 # --- Demo data --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:

延伸阅读