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

如何在R中为两组不同变量的数据集添加分组注释绘制热图

在R中绘制带分组注释的热图

R基础包的heatmap()函数确实不支持直接添加列分组注释,推荐用pheatmap包来实现你的需求,这个包专门针对热图的注释、分组定制做了优化,操作更灵活。

步骤1:安装并加载pheatmap包

如果还没安装,先执行安装命令:

install.packages("pheatmap")
library(pheatmap)

步骤2:准备数据(沿用你提供的代码)

为了保证结果可重复,先设置随机种子:

set.seed(123)
TFs <- c("IRF2", "IRF3", "IRF5", "IRF7", "STAT1")
columnnames <- c("IFN-alpha", "IFN-beta", "IFN-gamma", "Healthy", "Cancer", "Virus")
heatmap_matrix <- matrix(sample(1:30, 30), nrow=length(TFs))
colnames(heatmap_matrix) <- columnnames 
rownames(heatmap_matrix) <- TFs

步骤3:创建列分组注释元数据

根据你的分组规则,给每一列指定所属组别:

# 定义列分组信息
col_annotation <- data.frame(
  Group = factor(
    ifelse(colnames(heatmap_matrix) %in% c("IFN-alpha", "IFN-beta", "IFN-gamma"), 
           "干扰素处理组", "细胞状态组"),
    levels = c("干扰素处理组", "细胞状态组")
  )
)
# 确保注释数据的行名和热图列名完全匹配
rownames(col_annotation) <- colnames(heatmap_matrix)

步骤4:绘制带分组注释的热图

调用pheatmap()函数,传入注释数据即可生成带分组标识的热图:

pheatmap(
  heatmap_matrix,
  annotation_col = col_annotation, # 添加列分组注释栏
  annotation_colors = list( # 自定义注释栏颜色(可选)
    Group = c("干扰素处理组" = "#4292c6", "细胞状态组" = "#f8766d")
  ),
  cluster_cols = FALSE, # 保持列的原始顺序,不需要聚类则设为FALSE
  main = "转录因子表达热图(带分组注释)",
  fontsize_row = 10,
  fontsize_col = 9
)

额外调整选项

  • 若需要对行/列进行聚类,将cluster_rows/cluster_cols设为TRUE(默认值为TRUE)
  • 可通过color参数自定义热图的颜色渐变,例如:color = colorRampPalette(c("navy", "white", "firebrick3"))(100)
  • 若要隐藏热图的行/列名称,设置show_rownames = FALSE或show_colnames = FALSE

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:52:23