[R语言] Heatmap绘图经验总结
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[R语言] Heatmap绘图经验总结相关的知识,希望对你有一定的参考价值。
参考技术A 这里随机生成了25个0,1之间的均匀分布的随机数,其中,行是样本,列是特征,如图:第一种方案绘制的Heatmap需要借助于Corrplot包,我们求出dat特征的相关系数矩阵,进一步利用corrplot函数来画图,在该包的官方文档中,对于corrplot函数的参数描述可以说是非常多,这里我给出几种常用的参数:
method 表示热力图中每一块所展示的形状,可选值有: "circle", "square", "ellipse", "number", "shade", "color", "pie";
type 表示相关系数矩阵展示的方式,比如只展示上三角或下三角或者全部展示,可选值有:“full”,“upper","lower”;
tl.pos 指定文本标签(变量名称)的位置,当type=full时,默认标签位置在左边和顶部(lt),当type=lower时,默认标签在左边和对角线(ld),当type=upper时,默认标签在顶部和对角线,d表示对角线,n表示不添加文本标签;
diag 表示对角线上取值,默认为FALSE;
cl.pos 表示图例位置,当type=upper或full时,图例在右方,当type=lower时,图例在底部,不需要图例时,需指定该参数为n;
...
下面给出方法运用:
当然,利用corrplot函数画图可以实现图层的叠加,上面这张图就是分上下两部分完成的,其中默认的颜色样式个人觉得还是可以的,只不过对于相关系数值会根据高低颜色深浅会发生变化,对于一些相关性低的值颜色会非常浅,所以看得不是很明显。
关于这个包具体的的使用方法可以参考这位博主写的文章:
这里我们还是用方案一随机生成的矩阵,介绍用pheatmap包来绘制热力图。pheatmap包里关于绘制热力图的参数相对来说比较少,可以帮助我们快速的绘图,这里给出一些常用参数:
color 设置渐变的颜色,通常借助于colorRampPalette函数,比如说设置红黄蓝渐变,并在这之间分成50个等级,我们可以设置color=colorRampPalette(c("red","yellow","blue"))(50);
cluster_cols & cluster_rows 表示是否按行或列聚类,默认值为FALSE;
clustering_method 表示聚类方法,默认是complete,此外还"ward.D",“single”,“average”,等;
display_numbers 表示是否在heatmap里面显示数值,默认是FALSE;
show_rownames & show_colnames 表示是否显示行名或列名;
file 设置图片保存位置
...
下面给出方法运用
去掉边框线可能会好看一点:
由于是随机生成的数据,就不显示聚类的效果(只需要把cluster_row和cluster_col删掉即可),总体来说用pheatmap绘制热图会相对简单一点,但是毫不逊色于其他包绘制的热图。此外,如果想对于行或列来显示一些注释信息(annotation),比如将特征分成2类,每一类是不同的颜色,这里就可以先生成一个行名是特征,列名是分类结果的数据框,然后利用annotation_row(或col)参数,将生成的数据框赋给它即可,具体可以参考这位博主的文章:
接下来介绍的ComplexHeatmap包就比较全面了,他可以兼容pheatmap函数的所有功能,可以说是pheatmap包的加强版,能够创建更加复杂的热力图,如果你会pheatmap包的应用,那么在ComplexHeatmap包里面,你只需要指明是该包下的pheatmap函数即可使用(ComplexHeatmap::pheatmap())。接下来列举出一些常用参数:
name 、column_title、row_title设置图例、列标题与行标题的名字;
column_title_side & row_title_side 设置列标题与行标题的位置,之注意:列标题只能跟"top"或"buttom"参数,行标题只能跟"left"或"right"参数;
column_names_side & row_names_side 设置行名与列名的位置,后面跟的是位置参数,如"left"、"top"等;
column_names_rot & row_names_rot 设置行名与列名的倾斜角度,后面跟的是角度,如0、30、90等;
column_names_gp & row_names_gp 设置行名与列名的颜色,比如 column_names_gp =gpar(col=rep("red",5));
column_title_gp & row_title_gp 设置列与行标题的颜色,注意:这个需要和聚类分割的数量来决定,要指定row_split & column_split,颜色的设置才能生效;
col 设置渐变的颜色向量参数,这里推荐用RColorBrewer包中的颜色,比如 col = rev(brewer.pal(n = 7, name ="RdYlBu"));
cluster_rows & cluster_columns 表示是否对行列进行聚类,默认是TRUE;
cluster_rows & cluster_columns 表示是否对行列进行聚类,默认是TRUE,如果是特定值,则表示对聚类树进行处理;
row_dend_reorder & column_dend_reorder 表示将行或列进行排序,默认是TRUE,所以我们在利用这个包绘制相关系数热力图时,会看到对角线不是1,那么我们就需要检查是否设置了这个参数;
show_column_dend & show_row_dend 表示是否展示行与列的聚类树;
...
下面利用上述随机生成的数据来绘制heatmap:
最值得一提的是,cluster_rows参数,可以结合hlust函数来使用,并通过color_branches函数来为不同类别设置颜色,使得整个heatmap看起来更加美观。如果我们要显示聚类后的数据分割并命名,我们可以这样:
如若想得到更加详细的说明,可以看ComplexHeatmap包的官方文档,或者参见这位博主的文章:
当然,画heatmap怎么能少的了ggplot2呢,我们在利用ggplot画图时,只需要设置scale_fill_gradient即可,例如:scale_fill_gradient(low = "yellow", high = "red") 表示颜色从黄色到红色渐变。注意要把数据处理成ggplot所需要的样式!下面来绘制heatmap:
如果要实现聚类树在heatmap上,我们需要利用ggtree函数,分别绘制聚类树与热力图,最后用aplot包进行拼接即可。
由于ComplexHeatmap包绘制的热力图是一个Heatmap对象,故他与其他图形不同,自身可以与其他Heatmap对象结合,我们只需要利用"+"号或者"%v%"连接符对多个Heatmap对象进行水平或垂直连接就可以了。
当我们需要将pheatmap包绘制的热力图与ggplot画的其他图贴在一起时,我们可以利用ggplotify包来实现,具体操作流程为:
我们用上回利用iris数据集画组合小提琴图的例子,进一步组合heatmap:
当然ggplot也可以画heatmap,这里不再阐述,对于上面几种绘图方案,我们只需选取一种最美观,最有效的方式来画heatmap即可。
R语言热力图综合教程-heatmapd3heatmap和ComplexHeatmap
用于绘制交互式和静态热图的R包和功能很多,包括:
heatmap()[R基本函数,统计数据包]:绘制一个简单的热图
heatmap.2()[ gplots R包]:与R base函数相比,绘制了增强的热图。
pheatmap()[ pheatmap R包]:绘制漂亮的热图,并提供更多控件来更改热图的外观。
d3heatmap()[ d3heatmap R包]:绘制交互式/可单击的热图
ComplexHeatmap R / Bioconductor的包]:绘制,注释和排列复杂热图(用于基因组数据分析是非常有用的)
在这里,我们从描述绘制热图的5 R函数开始。接下来,我们将重点介绍ComplexHeatmap程序包,该程序包提供了一种灵活的解决方案来安排和注释多个热图。它也可以可视化来自不同来源的不同数据之间的关联
我们使用mtcars数据作为演示数据集。我们首先将数据标准化以使变量具有可比性:
df <- scale(mtcars)
# Default plot
heatmap(df, scale = "none")
如何指定调色板
col<- colorRampPalette(c("red", "white", "blue"))(256)
heatmap(df, scale = "none", col = col)
library("RColorBrewer")
col <- colorRampPalette(brewer.pal(10, "RdYlBu"))(256)
heatmap(df, scale = "none", col = col)
此外,可以使用参数RowSideColors和ColSideColors分别注释行和列。
例如,在下面的R代码中,将自定义热图,如下所示:
RColorBrewer调色板名称用于更改外观
参数RowSideColors和ColSideColors分别用于注释行和列。按照行列顺序指指定颜色
heatmap是按照聚类来重排行列的,会打乱颜色。
# Use RColorBrewer color palette names
library("RColorBrewer")
col <- colorRampPalette(brewer.pal(10, "RdYlBu"))(256)
heatmap(df, scale = "none", col = col,
RowSideColors = rep(c("blue", "pink"), each = 16),
ColSideColors = c(rep("purple", 5), rep("orange", 6)))
# install.packages("gplots")
library("gplots")
heatmap.2(df, scale = "none", col = bluered(100),
trace = "none", density.info = "none")
pheatmap
这个功能十分强大,出图我们也经常选用,cutree_rows参数用于按照聚类结果进行切割。
library("pheatmap")
pheatmap(df, cutree_rows = 4)
# install.packages("d3heatmap")
library("d3heatmap")
d3heatmap(scale(mtcars), colors = "RdYlBu",
k_row = 4, # Number of groups in rows
k_col = 2 # Number of groups in columns
)
pheatmap不能使用。
ComplexHeatmap 功能十分强大
row_names_gp:设置标签自字体大小
olumn_title:设置行,列名称标签。
library(ComplexHeatmap)
Heatmap(df,
name = "mtcars", #title of legend
column_title = "Variables", row_title = "Samples",
row_names_gp = gpar(fontsize = 7) # Text size for row names
)
要指定自定义颜色,必须使用colorRamp2()函数[ circlize package],如下所示:
library(circlize)
mycols <- colorRamp2(breaks = c(-2, 0, 2),
colors = c("green", "white", "red"))
Heatmap(df, name = "mtcars", col = mycols)
更换调色板,使用RColorBrewer 中的颜色。
library("circlize")
library("RColorBrewer")
Heatmap(df, name = "mtcars",
col = colorRamp2(c(-2, 0, 2), brewer.pal(n=3, name="RdBu")))
dendextend 同样给复杂热图聚类上色。
library(dendextend)
row_dend = hclust(dist(df)) # row clustering
col_dend = hclust(dist(t(df))) # column clustering
Heatmap(df, name = "mtcars",
row_names_gp = gpar(fontsize = 6.5),
cluster_rows = color_branches(row_dend, k = 4),
cluster_columns = color_branches(col_dend, k = 2))
复杂热图按照聚类切割分块
km/row_km:对列进行聚类拆分
# Divide into 2 groups
set.seed(2)
Heatmap(df, name = "mtcars", km = 4)
按照行进行分割聚类:column_km
# Divide into 2 groups
set.seed(2)
Heatmap(df, name = "mtcars", column_km = 4)
指定行列分隔
split :参数用于指定行的分组,用于分割热图。row_split一样
如果要对行进行聚类,使用column_split,用法一样。
# Split
# data.frame(cyl = rep(1:4,dim(mtcars)[2]))
Heatmap(df, name ="mtcars",
split = data.frame(cyl = mtcars$cyl),
column_split = data.frame(cyl = rep(1:2,dim(mtcars)[2])[1:11]),
row_names_gp = gpar(fontsize = 7))
多重分隔
Heatmap(df, name ="mtcars", col = col,
km = 4, split = mtcars$cyl)
library("cluster")
set.seed(2)
pa = pam(df, k = 3)
Heatmap(df, name = "mtcars", col = col,
split = paste0("pam", pa$clustering))
复杂热图为什么复杂
复杂热图最强大的莫过于对于热图的注释
df <- t(df)
# Define some graphics to display the distribution of columns
.hist = anno_histogram(df, gp = gpar(fill = "lightblue"))
.density = anno_density(df, type = "line", gp = gpar(col = "blue"))
ha_mix_top = HeatmapAnnotation(hist = .hist, density = .density)
# Define some graphics to display the distribution of rows
.violin = anno_density(df, type = "violin",
gp = gpar(fill = "lightblue"), which = "row")
.boxplot = anno_boxplot(df, which = "row")
ha_mix_right = HeatmapAnnotation(violin = .violin, bxplt = .boxplot,
which = "row", width = unit(4, "cm"))
# Combine annotation with heatmap
Heatmap(df, name = "mtcars",
column_names_gp = gpar(fontsize = 8),
top_annotation = ha_mix_top) + ha_mix_right
复杂热图的组合
# Heatmap 1
ht1 = Heatmap(df, name = "ht1", km = 2,
column_names_gp = gpar(fontsize = 9))
# Heatmap 2
ht2 = Heatmap(df, name = "ht2",
col = circlize::colorRamp2(c(-2, 0, 2), c("green", "white", "red")),
column_names_gp = gpar(fontsize = 9))
# Combine the two heatmaps
ht1 + ht2
细布控制组合
draw(ht1 + ht2,
row_title = "Two heatmaps, row title",
row_title_gp = gpar(col = "red"),
column_title = "Two heatmaps, column title",
column_title_side = "bottom",
# Gap between heatmaps
gap = unit(0.5, "cm"))
expr <- readRDS(paste0(system.file(package = "ComplexHeatmap"),
"/extdata/gene_expression.rds"))
mat <- as.matrix(expr[, grep("cell", colnames(expr))])
type <- gsub("s\d+_", "", colnames(mat))
ha = HeatmapAnnotation(df = data.frame(type = type))
ha
## A HeatmapAnnotation object with 1 annotation
## name: heatmap_annotation_2
## position: column
## items: 24
## width: 1npc
## height: 5mm
## this object is subsetable
## 9.001mm extension on the right
##
## name annotation_type color_mapping height
## type discrete vector random 5mm
Heatmap(mat, name = "expression", km = 5, top_annotation = ha,
# top_annotation_height = unit(4, "mm"),
show_row_names = FALSE, show_column_names = FALSE) +
Heatmap(expr$length, name = "length", width = unit(5, "mm"),
col = circlize::colorRamp2(c(0, 100000), c("white", "orange"))) +
Heatmap(expr$type, name = "type", width = unit(5, "mm")) +
Heatmap(expr$chr, name = "chr", width = unit(5, "mm"),
col = circlize::rand_color(length(unique(expr$chr))))
ha = HeatmapAnnotation(df = data.frame(type = type))
ha
## A HeatmapAnnotation object with 1 annotation
## name: heatmap_annotation_3
## position: column
## items: 24
## width: 1npc
## height: 5mm
## this object is subsetable
## 9.001mm extension on the right
##
## name annotation_type color_mapping height
## type discrete vector random 5mm
Heatmap(mat, name = "expression", km = 5, top_annotation = ha,
# top_annotation_height = unit(4, "mm"),
show_row_names = FALSE, show_column_names = FALSE) +
Heatmap(expr$type, name = "type", width = unit(5, "mm")) +
Heatmap(expr$type, name = "type", width = unit(5, "mm"))
如何添加多个行,或者列
# Annotation data frame
annot_df <- data.frame(cyl = mtcars$cyl, am = mtcars$am,
mpg = mtcars$mpg)
# row.names(annot_df) = row.names(mtcars)
# Define colors for each levels of qualitative variables
# Define gradient color for continuous variable (mpg)
col = list(cyl = c("4" = "green", "6" = "gray", "8" = "darkred"),
am = c("0" = "yellow", "1" = "orange"),
mpg = circlize::colorRamp2(c(17, 25),
c("lightblue", "purple")) )
# Create the heatmap annotation
ha <- HeatmapAnnotation(df = data.frame(cyl = mtcars$cyl, am = mtcars$am,
mpg = mtcars$mpg), col = col)
# Combine the heatmap and the annotation
# df = t(df)
Heatmap(df, name = "mtcars",
top_annotation = ha)
# Annotation data frame
annot_df <- data.frame(cyl = mtcars$cyl, am = mtcars$am,
mpg = mtcars$mpg)
# row.names(annot_df) = row.names(mtcars)
# Define colors for each levels of qualitative variables
# Define gradient color for continuous variable (mpg)
col = list(cyl = c("4" = "green", "6" = "gray", "8" = "darkred"),
am = c("0" = "yellow", "1" = "orange"),
mpg = circlize::colorRamp2(c(17, 25),
c("lightblue", "purple")) )
# Create the heatmap annotation
ha <- HeatmapAnnotation(df = data.frame(cyl = mtcars$cyl, am = mtcars$am,
mpg = mtcars$mpg), col = col)
# Combine the heatmap and the annotation
df = t(df)
Heatmap(df, name = "mtcars") +
Heatmap(mtcars$mpg, name = "type", width = unit(5, "mm")) +
Heatmap(mtcars$mpg, name = "type", width = unit(5, "mm"))
Heatmap(df, name = "mtcars") +
Heatmap(annot_df , name = "type", width = unit(5, "mm"))
densityHeatmap(scale(mtcars))
reference
https://www.datanovia.com/en/lessons/heatmap-in-r-static-and-interactive-visualization/
如需联系EasyShu团队
https://github.com/Easy-Shu/EasyShu-WeChat
数据可视化之美系列书籍
Github
https://github.com/Easy-Shu/Beautiful-Visualization-with-python
Github
https://github.com/Easy-Shu/Beautiful-Visualization-with-R
以上是关于[R语言] Heatmap绘图经验总结的主要内容,如果未能解决你的问题,请参考以下文章
R语言实战应用精讲50篇(二十七)-时空数据分析-经验空间/时间均值(latex公式+R代码绘图)