简介
本文将绘制静态与交互式热图,需要使用到以下R包和函数:
● heatmap():用于绘制简单热图的函数
● heatmap.2():绘制增强热图的函数
● d3heatmap:用于绘制交互式热图的R包
● ComplexHeatmap:用于绘制、注释和排列复杂热图的R&bioconductor包(非常适用于基因组数据分析)
数据准备
使用R内置数据集 mtcars
df <- as.matrix((scale(mtcars))) #归一化、矩阵化
使用基本函数绘制简单简单热图
主要是函数 heatmap(x, scale="row")
● x: 数据矩阵
● scale:表示不同方向,可选值有:row, columa, none
● Default plotheatmap(df, scale = "none")
Use custom colorscol <- colorRampPalette(c("red", "white", "blue"))(256)heatmap(df, scale = "none", col=col)
#Use RColorBrewer color palette names
library(RColorBrewer)col <- colorRampPalette(brewer.pal(10, "RdYlBu"))(256)#自设置调色板dim(df)#查看行列数
## [1] 32 11
heatmap(df, scale = "none", col=col, RowSideColors = rep(c("blue", "pink"), each=16),
ColSideColors = c(rep("purple", 5), rep("orange", 6)))
#参数RowSideColors和ColSideColors用于分别注释行和列颜色等,可help(heatmap)详情
增强热图
函数 heatmap.2()
在热图绘制方面提供许多扩展,此函数包装在 gplots 包里。
library(gplots)heatmap.2(df, scale = "none", col=bluered(100),
trace = "none", density.info = "none")#还有其他参数可参考help(heatmap.2())
交互式热图绘制
d3heatmap 包可用于生成交互式热图绘制,可通过以下代码生成:
if (!require("devtools"))
install.packages("devtools")
devtools::install_github("rstudio/d3heatmap")
函数 d3heatmap() 用于创建交互式热图,有以下功能:
● 将鼠标放在感兴趣热图单元格上以查看行列名称及相应值
● 可选择区域进行缩放
library(d3heatmap)d3heatmap(df, colors = "RdBu", k_row = 4, k_col = 2)
k_row、k_col分别指定用于对行列中树形图分支进行着色所需组数。进一步信息可help(d3heatmap())获取。
使用 dendextend 包增强热图
软件包 dendextend 可以用于增强其他软件包的功能
library(dendextend)# order for rows Rowv <- mtcars %>% scale %>% dist %>% hclust %>% as.dendrogram %>% set("branches_k_color", k = 3) %>% set("branches_lwd", 1.2) %>% ladderize# Order for columns# We must transpose the data Colv <- mtcars %>% scale %>% t %>% dist %>% hclust %>% as.dendrogram %>% set("branches_k_color", k = 2, value = c("orange", "blue")) %>% set("branches_lwd", 1.2) %>% ladderize #增强heatmap()函数 heatmap(df, Rowv = Rowv, Colv = Colv, scale = "none")
#增强heatmap.2()函数
heatmap.2(df, scale = "none", col = bluered(100), Rowv = Rowv, Colv = Colv, trace = "none", density.info = "none")