如何在pheatmap中添加行/列轴标签(保留原有行名与列名)
pheatmap添加行/列轴标签的方法
pheatmap不属于ggplot原生绘图体系,无法直接套用ylab()/xlab()的ggplot语法,有三种常用实现方式:
方法1:使用pheatmap内置参数(最简便)
pheatmap本身自带轴标签设置参数,直接传入即可快速生成标签:
library(pheatmap) library(reshape2) df = data.frame(r = c(1:3), foo = c("a","b", "c"), val = c(5,10,15), stringsAsFactors = F) heatmat = reshape2::acast(df, foo~r, fill = 0, value.var = "val") # 直接指定列标签xlab、行标签ylab p <- pheatmap(heatmat, xlab = "r", ylab = "foo")
该方法无需额外依赖,缺点是默认标签位置、字体样式灵活度低,适合快速出图场景。
方法2:基于grid系统自定义标签(灵活度最高)
pheatmap基于grid绘图系统构建,可在热图绘制完成后手动添加标签,自由调整位置、字体、旋转角度等属性:
library(pheatmap) library(reshape2) library(grid) df = data.frame(r = c(1:3), foo = c("a","b", "c"), val = c(5,10,15), stringsAsFactors = F) heatmat = reshape2::acast(df, foo~r, fill = 0, value.var = "val") # 绘制基础热图,可通过padding参数预留边距避免标签被截断 p <- pheatmap(heatmat, padding = 0.08) # 添加横轴(列方向)标签 grid.text(label = "r", x = 0.5, # 水平居中,取值范围0~1对应画布从左到右 y = 0.03, # 距底部距离,取值越小越靠下 gp = gpar(fontsize = 12, fontface = "bold")) # 添加纵轴(行方向)标签 grid.text(label = "foo", x = 0.03, # 距左侧距离,取值越小越靠左 y = 0.5, # 垂直居中 rot = 90, # 标签旋转90度适配纵轴 gp = gpar(fontsize = 12, fontface = "bold"))
方法3:转为ggplot对象后使用ggplot语法调整
如果习惯ggplot的操作逻辑,可借助ggplotify包将pheatmap对象转换为ggplot类,后续完全按照ggplot的语法调整标签、主题:
library(pheatmap) library(reshape2) library(ggplotify) df = data.frame(r = c(1:3), foo = c("a","b", "c"), val = c(5,10,15), stringsAsFactors = F) heatmat = reshape2::acast(df, foo~r, fill = 0, value.var = "val") # 转为ggplot对象 p <- as.ggplot(pheatmap(heatmat)) # 按ggplot习惯设置标签、样式 p + xlab("r") + ylab("foo") + theme(axis.title = element_text(size = 12, face = "bold"))
内容的提问来源于stack exchange,提问作者Rahi
相关产品推荐
相关产品推荐

