R语言pheatmap自定义列注释颜色失效问题求助
解决pheatmap列注释自定义颜色不生效问题
问题背景
绘制基因表达数据热图时,尝试为列添加基因功能注释并自定义注释颜色,代码可正常运行,但列注释始终使用默认颜色,怀疑是颜色/基因功能矩阵维度或pheatmap读取注释的方式存在问题。
核心原因
- 注释颜色列表键名不匹配:
annotation_col传入的注释数据框gene_col中,注释列名称是gene_function,但自定义颜色列表gene_col_colors使用的键是group,两者无法对应,pheatmap因此无法识别自定义颜色, fallback到默认配色。 - 分组名称维度问题:
col_groups被转为数据框,直接用于命名颜色向量时可能出现维度不兼容,需转为向量格式。
修正方案
关键代码修正
将颜色列表的键名改为与gene_col的列名一致,并将分组名称转为向量:
# 提取唯一功能分组,转为向量格式 col_groups <- unique(name_function_matrix[,2]) # 自定义颜色列表,键名匹配annotation_col的列名gene_function gene_col_colors <- list(gene_function = c("blue","green","cyan","gray","red")) # 为颜色向量命名,对应功能分组 names(gene_col_colors$gene_function) <- col_groups
完整修正后的代码
library(dplyr, warn.conflicts = FALSE) library(tidyverse) library(pheatmap) library(dendsort) library(RColorBrewer) Data <- read.table("PathToFile/Data.txt",sep="\t",header=TRUE, quote="", fill = TRUE) row.names(Data) <- Data$gene Data <- Data[, -1] FilteredData = Data %>% filter(if_any(everything(), function(x) x <=-3 | x >=3)) transposedData = t(FilteredData) sort_hclust <- function(...) as.hclust(dendsort(as.dendrogram(...))) clrsp <- colorRampPalette(c("blue", "black", "yellow")) clrs <- clrsp(10) breaks1 <- seq(-10, 10, length.out = 10) # 拆分基因名与功能注释 name_function_matrix <- str_split_fixed(colnames(transposedData), "_", 2) gene_col <- data.frame(row.names = name_function_matrix[,1], gene_function = name_function_matrix[,2]) colnames(transposedData) <- rownames(gene_col) # 提取唯一功能分组(转为向量) col_groups <- unique(name_function_matrix[,2]) # 构建匹配的自定义颜色列表 gene_col_colors <- list(gene_function = c("blue","green","cyan","gray","red")) names(gene_col_colors$gene_function) <- col_groups print(gene_col_colors) pheatmap(transposedData, clustering_distance_rows = "correlation", clustering_distance_cols = "euclidean", cluster_rows = TRUE, cluster_cols = TRUE, annotation_col = gene_col, annotation_colors = gene_col_colors, clustering_method = "centroid", show_rownames = TRUE, show_colnames = FALSE, scale = "none", color = clrs, breaks = breaks1, cellwidth = 0.2, cellheight = 10, fontsize = 5, fontsize_row = 5, fontsize_col = 3, treeheight_col = 0, treeheight_row = 20, filename = "PathToFile/imageX.png")
验证说明
修正后,annotation_colors中的键名gene_function与annotation_col数据框的列名完全匹配,同时分组名称以向量格式传入,确保颜色与功能注释一一对应,pheatmap将正确应用自定义颜色。
内容的提问来源于stack exchange,提问作者timnick23
相关产品推荐
相关产品推荐

