# 加载必要的包
library(ComplexHeatmap)
library(circlize)
library(RColorBrewer)
# 读取已生成的数据
exp_matrix <- as.matrix(read.csv("heatmap_expression_matrix.csv", row.names = 1))
sample_annotation <- read.csv("heatmap_sample_metadata.csv")
# 对表达矩阵进行 Z-score 标准化(按行)
exp_matrix_scaled <- t(scale(t(exp_matrix)))
# 创建基因注释:前 25 个基因属于 Pathway_Alpha,后 25 个属于 Pathway_Beta
gene_pathway <- data.frame(
Gene = rownames(exp_matrix_scaled),
Pathway = c(rep("Pathway_Alpha", 25), rep("Pathway_Beta", 25))
)
# 模拟 Immune Score(每个样本一个分数)
set.seed(2024)
immune_score <- runif(ncol(exp_matrix_scaled), min = 0, max = 100)
# === 1. 定义颜色方案 ===
# 热图主体:蓝-白-红渐变
col_fun <- colorRamp2(c(-2, 0, 2), c("#2166AC", "white", "#B2182B"))
# 顶部注释颜色:Nature NPG 风格
stage_colors <- c("Stage_I" = "#E64B35", "Stage_IV" = "#4DBBD5")
gender_colors <- c("Male" = "#00A087", "Female" = "#F39B7F")
# === 2. 构建顶部注释 (Top Annotation) ===
top_annotation <- HeatmapAnnotation(
Stage = sample_annotation$Stage,
Gender = sample_annotation$Gender,
col = list(
Stage = stage_colors,
Gender = gender_colors
),
annotation_name_side = "left",
annotation_name_gp = gpar(fontsize = 10, fontface = "bold")
)
# === 3. 构建底部注释 (Bottom Annotation) - Immune Score 柱状图 ===
bottom_annotation <- HeatmapAnnotation(
`Immune Score` = anno_barplot(
immune_score,
gp = gpar(fill = "#8491B4", col = NA),
height = unit(2, "cm"),
axis_param = list(side = "right", gp = gpar(fontsize = 8))
),
annotation_name_side = "left",
annotation_name_gp = gpar(fontsize = 10, fontface = "bold")
)
# === 4. 构建左侧注释 (Row Annotation) - Pathway ===
row_annotation <- rowAnnotation(
Pathway = gene_pathway$Pathway,
col = list(Pathway = c("Pathway_Alpha" = "#7570B3", "Pathway_Beta" = "#E7298A")),
annotation_name_gp = gpar(fontsize = 10, fontface = "bold"),
show_legend = TRUE
)
# === 5. 绘制 ComplexHeatmap ===
ht <- Heatmap(
exp_matrix_scaled,
name = "Z-score",
# 颜色设置
col = col_fun,
# 聚类设置
cluster_rows = TRUE,
cluster_columns = TRUE,
show_row_dend = TRUE,
show_column_dend = TRUE,
# 切分设置
row_split = gene_pathway$Pathway,
column_split = sample_annotation$Stage,
row_title = "Pathway",
column_title = "Clinical Stage",
# 标签显示
show_row_names = TRUE,
show_column_names = FALSE, # 隐藏样本名称
row_names_gp = gpar(fontsize = 8),
# 添加注释
top_annotation = top_annotation,
bottom_annotation = bottom_annotation,
left_annotation = row_annotation,
# 热图边框
border = TRUE,
rect_gp = gpar(col = "white", lwd = 0.5),
# 图例设置
heatmap_legend_param = list(
title = "Expression\n(Z-score)",
title_gp = gpar(fontsize = 10, fontface = "bold"),
labels_gp = gpar(fontsize = 9),
legend_height = unit(4, "cm"),
legend_direction = "vertical"
),
# 行列标题样式
row_title_gp = gpar(fontsize = 12, fontface = "bold"),
column_title_gp = gpar(fontsize = 12, fontface = "bold")
)
# 绘制热图
draw(ht,
heatmap_legend_side = "right",
annotation_legend_side = "right",
merge_legend = TRUE)