查看原文
其他

超详细的R语言热图之complexheatmap系列6

阿越 医学和生信笔记 2023-02-25

我们继续学习complexheatmap包的内容,这是本系列的第6篇文章。本系列内容非常多,将通过多篇推文逐渐介绍,欢迎大家关注我的公众号:医学和生信笔记

本篇内容主要介绍热图中图例的各种设置!


complexheatmap系列第1篇:超详细的R语言热图之complexheatmap系列1

complexheatmap系列第2篇:超详细的R语言热图之complexheatmap系列2

complexheatmap系列第3篇:超详细的R语言热图之complexheatmap系列3

complexheatmap系列第4篇:超详细的R语言热图之complexheatmap系列4

complexheatmap系列第5篇:超详细的R语言热图之complexheatmap系列5

第五章 图例

简单图例会自动绘出,复杂图例需要手动修改。所有的图例都可以通过Legend()函数画出,都属于Legend类。热图主体的图例可以通过heatmap_legend_param参数(Heatmap()中)调整,注释条的图例可以通过annatation_legend_param参数(HeatmapAnnotation()中)调整。

5.1 连续性变量的图例

library(ComplexHeatmap)
## 载入需要的程辑包:grid
## ========================================
## ComplexHeatmap version 2.8.0
## Bioconductor page: http://bioconductor.org/packages/ComplexHeatmap/
## Github page: https://github.com/jokergoo/ComplexHeatmap
## Documentation: http://jokergoo.github.io/ComplexHeatmap-reference
## 
## If you use it in published research, please cite:
## Gu, Z. Complex heatmaps reveal patterns and correlations in multidimensional 
##   genomic data. Bioinformatics 2016.
## 
## The new InteractiveComplexHeatmap package can directly export static 
## complex heatmaps into an interactive Shiny app with zero effort. Have a try!
## 
## This message can be suppressed by:
##   suppressPackageStartupMessages(library(ComplexHeatmap))
## ========================================
library(circlize)
## ========================================
## circlize version 0.4.13
## CRAN page: https://cran.r-project.org/package=circlize
## Github page: https://github.com/jokergoo/circlize
## Documentation: https://jokergoo.github.io/circlize_book/book/
## 
## If you use it in published research, please cite:
## Gu, Z. circlize implements and enhances circular visualization
##   in R. Bioinformatics 2014.
## 
## This message can be suppressed by:
##   suppressPackageStartupMessages(library(circlize))
## ========================================
col_fun = colorRamp2(c(00.51), c("blue""white""red"))
lgd = Legend(col_fun = col_fun, title = "foo")
draw(lgd)

简单图例会自动绘出:

Heatmap(matrix(rnorm(100),10),
        top_annotation = HeatmapAnnotation(foo = 1:10)
        )
plot of chunk unnamed-chunk-2

当然也可以使用参数手动指定,改变样式等:

Heatmap(matrix(rnorm(100), 10), 
    heatmap_legend_param = list(
        title = "rnorm", at = c(-202), 
        labels = c("neg_two""zero""pos_two")
    ),
    top_annotation = HeatmapAnnotation(
        foo = 1:10,
        annotation_legend_param = list(foo = list(title = "foo_top_anno"))
    ))
plot of chunk unnamed-chunk-3

可以自由设置图例刻度位置、标签、图例标题、高度、宽度、标签颜色、字体等:

lgd <- Legend(col_fun = col_fun, title = "foo1", at = c(0,0.25,0.5,0.75,1))
draw(lgd)
lgd <- Legend(col_fun = col_fun, title = "foo2", at = c(0,0.25,0.5,0.75,1),
              labels = c("hi","ha","hei","hoo","hey"))
draw(lgd)
plot of chunk unnamed-chunk-5
legd <- Legend(col_fun = col_fun, title = "foo3", legend_height = unit(8"cm"))
draw(legd)
plot of chunk unnamed-chunk-6
lgd <- Legend(col_fun = col_fun, title = "foo1", grid_width = unit(3"cm")) # 竖直型的图例用`grid_width`
draw(lgd)
plot of chunk unnamed-chunk-7

修改图例标签样式:

lgd <- Legend(col_fun = col_fun, title = "foo", legend_gp = gpar(col = "red", font = 5))
draw(lgd)
plot of chunk unnamed-chunk-8

修改图例边框颜色:

lgd <- Legend(col_fun = col_fun, title = "foo", border = "red")
draw(lgd)
plot of chunk unnamed-chunk-9

修改图例标题位置:

lgd <- Legend(col_fun = col_fun, title = "foooooooo", title_position = "leftcenter-rot",
    legend_height = unit(4"cm"))
draw(lgd)
plot of chunk unnamed-chunk-10

使用特殊字体,公式等:

lgd <- Legend(col_fun = col_fun, title = expression(hat(beta) == (X^t * X)^{-1} * X^t * y), 
    at = c(00.250.50.751), labels = expression(alpha, beta, gamma, delta, epsilon))
draw(lgd)
plot of chunk unnamed-chunk-11

旋转图例标签:

lgd <- Legend(col_fun = col_fun, name = "foo1", labels_rot = 90)
draw(lgd)
plot of chunk unnamed-chunk-12

标签拥挤会自动调整:

lgd <- Legend(col_fun = col_fun, title = "foo", at = c(00.10.150.50.90.951))
draw(lgd)
plot of chunk unnamed-chunk-13

水平排列的图例,只需要一个参数:direction="horizontal"除了图例宽度使用legend_width外,其余调整和竖直型完全一样,就不在详细介绍了。

lgd <- Legend(col_fun = col_fun, title = "foooooooo", direction = "horizontal"
    title_position = "lefttop")
draw(lgd)
plot of chunk unnamed-chunk-14

5.2 离散型变量的图例

基本上和连续性图例一模一样,就不多说了~~

lgd <- Legend(at = 1:6, title = "foo", legend_gp = gpar(fill = 1:6))
draw(lgd)
plot of chunk unnamed-chunk-15
lgd <- Legend(labels = month.name[1:6], title = "foo", legend_gp = gpar(fill = 1:6))
draw(lgd)
plot of chunk unnamed-chunk-16

离散图例展示连续性颜色映射:

at <- seq(01, by = 0.2)
lgd <- Legend(at = at, title = "foo", legend_gp = gpar(fill = col_fun(at)))
draw(lgd)
plot of chunk unnamed-chunk-17

离散型图例比连续型图例多了一个变成多列/多行的功能:

lgd <- Legend(labels = month.name[1:10], legend_gp = gpar(fill = 1:10), 
    title = "foo", ncol = 3)
draw(lgd)
plot of chunk unnamed-chunk-18

还可以改变图例形状,配合typepch参数:

lgd <- Legend(labels = month.name[1:6], title = "foo", type = "points"
    pch = 1:6, legend_gp = gpar(col = 1:6), background = "#FF8080")
draw(lgd)
plot of chunk unnamed-chunk-19
lgd <- Legend(labels = month.name[1:6], title = "foo", type = "points"
    pch = letters[1:6], legend_gp = gpar(col = 1:6), background = "white")
draw(lgd)
plot of chunk unnamed-chunk-20
lgd <- Legend(labels = month.name[1:6], title = "foo", type = "lines"
    legend_gp = gpar(col = 1:6, lty = 1:6), grid_width = unit(1"cm"))
draw(lgd)
plot of chunk unnamed-chunk-21
lgd <- Legend(labels = month.name[1:6], title = "foo", type = "boxplot",
    legend_gp = gpar(fill = 1:6))
draw(lgd)
plot of chunk unnamed-chunk-22
lgd <- Legend(labels = paste0("pch = "26:28), type = "points", pch = 26:28)
draw(lgd)
plot of chunk unnamed-chunk-23

5.3 多个图例

使用packLegend()排列多个图例,默认会绘制好图例,如果需要手动修改需要用到。

lgd1 <- Legend(at = 1:6, legend_gp = gpar(fill = 1:6), title = "legend1")
lgd2 <- Legend(col_fun = col_fun, title = "legend2", at = c(00.250.50.751))
lgd3 <- Legend(labels = month.name[1:3], legend_gp = gpar(fill = 7:9), title = "legend3")

pd <- packLegend(lgd1, lgd2, lgd3)
# 和下面相同 
pd <- packLegend(list = list(lgd1, lgd2, lgd3))
draw(pd)
plot of chunk unnamed-chunk-24

变成多列/多行,改变行间距/列间距等:

lgd1 <- Legend(at = 1:6, legend_gp = gpar(fill = 1:6), title = "legend1",
    nr = 1)
lgd2 <- Legend(col_fun = col_fun, title = "legend2", at = c(00.250.50.751),
    direction = "horizontal")

pd <- packLegend(lgd1, lgd2, lgd3, lgd1, lgd2, lgd3, max_width = unit(10"cm"), 
    direction = "horizontal", column_gap = unit(5"mm"), row_gap = unit(1"cm"))
draw(pd)
plot of chunk unnamed-chunk-25

5.4 热图主体和注释条的图例

主要是heatmap_legend_paramannotation_legend_param

m <- matrix(rnorm(100), 10)
Heatmap(m, name = "mat", heatmap_legend_param = list(
    at = c(-202),
    labels = c("low""zero""high"),
    title = "Some values",
    legend_height = unit(4"cm"),
    title_position = "lefttop-rot"
))
plot of chunk unnamed-chunk-26
ha <- HeatmapAnnotation(foo = runif(10), bar = sample(c("f""m"), 10, replace = TRUE),
    annotation_legend_param = list(
        foo = list(
                title = "Fooooooh",
                at = c(00.51),
                labels = c("zero""median""one")
            ),
        bar = list(
                title = "Baaaaaaar",
                at = c("f""m"),
                labels = c("Female""Male")
            )
))
Heatmap(m, name = "mat", top_annotation = ha)
plot of chunk unnamed-chunk-27

5.5 添加自定义图例

熟悉几个常用函数及参数后,剩下的就是各种排列组合,可以尽情发挥你的想象力。

ha1 = HeatmapAnnotation(pt = anno_points(1:10, gp = gpar(col = rep(2:3, each = 5)), 
    height = unit(2"cm")), show_annotation_name = FALSE)
ha2 = HeatmapAnnotation(ln = anno_lines(cbind(1:1010:1), gp = gpar(col = 4:5, lty = 1:2),
    height = unit(2"cm")), show_annotation_name = FALSE)
m = matrix(rnorm(100), 10)
ht_list = Heatmap(m, name = "mat1", top_annotation = ha1) + 
          Heatmap(m, name = "mat2", top_annotation = ha2) +
          Heatmap(m[, 1], name = "mat3"
            top_annotation = HeatmapAnnotation(
                summary = anno_summary(gp = gpar(fill = 2:3))
          ), width = unit(1"cm"))
draw(ht_list, ht_gap = unit(7"mm"), row_km = 2)
plot of chunk unnamed-chunk-28
lgd_list = list(
    Legend(labels = c("red""green"), title = "pt", type = "points", pch = 16
        legend_gp = gpar(col = 2:3)),
    Legend(labels = c("darkblue""lightblue"), title = "ln", type = "lines"
        legend_gp = gpar(col = 4:5, lty = 1:2)),
    Legend(labels = c("group1""group2"), title = "km", type = "boxplot",
        legend_gp = gpar(fill = 2:3))
)
draw(ht_list, ht_gap = unit(7"mm"), row_km = 2, annotation_legend_list = lgd_list)
plot of chunk unnamed-chunk-29

5.6 图例位置

一个参数的事情

ha1 = HeatmapAnnotation(foo1 = runif(10), bar1 = sample(c("f""m"), 10, replace = TRUE),
    annotation_legend_param = list(
        foo1 = list(direction = "horizontal"),
        bar1 = list(nrow = 1)))
ha2 = HeatmapAnnotation(foo2 = runif(10), bar2 = sample(c("f""m"), 10, replace = TRUE),
    annotation_legend_param = list(
        foo2 = list(direction = "horizontal"),
        bar2 = list(nrow = 1)))
ht_list = Heatmap(m, name = "mat1", top_annotation = ha1, 
        heatmap_legend_param = list(direction = "horizontal")) +
    rowAnnotation(sth = runif(10), 
        annotation_legend_param = list(sth = list(direction = "horizontal"))) +
    Heatmap(m, name = "mat2", top_annotation = ha2,
        heatmap_legend_param = list(direction = "horizontal"))
draw(ht_list, merge_legend = TRUE, heatmap_legend_side = "bottom"
    annotation_legend_side = "bottom")
plot of chunk unnamed-chunk-30

第六章 热图装饰

热图的每个组成部分都可以在画完之后继续修改,可以通过list_components()函数获取每个组成部分的名字,下面是作者给的例子。

set.seed(123)
mat = matrix(rnorm(802), 810)
mat = rbind(mat, matrix(rnorm(40, -2), 410))
rownames(mat) = paste0("R"1:12)
colnames(mat) = paste0("C"1:10)

ha_column1 = HeatmapAnnotation(points = anno_points(rnorm(10)), 
    annotation_name_side = "left")
ht1 = Heatmap(mat, name = "ht1", km = 2, column_title = "Heatmap 1"
    top_annotation = ha_column1, row_names_side = "left")

ha_column2 = HeatmapAnnotation(type = c(rep("a"5), rep("b"5)),
    col = list(type = c("a" = "red""b" = "blue")))
ht2 = Heatmap(mat, name = "ht2", row_title = "Heatmap 2", column_title = "Heatmap 2",
    bottom_annotation = ha_column2, column_km = 2)

ht_list = ht1 + ht2 + 
    rowAnnotation(bar = anno_barplot(rowMeans(mat), width = unit(2"cm")))
draw(ht_list, row_title = "Heatmap list", column_title = "Heatmap list")
plot of chunk unnamed-chunk-31
list_components()
##  [1] "ROOT"                           "global"                        
##  [3] "global_layout"                  "global-heatmaplist"            
##  [5] "main_heatmap_list"              "heatmap_ht1"                   
##  [7] "ht1_heatmap_body_wrap"          "ht1_heatmap_body_1_1"          
##  [9] "ht1_heatmap_body_2_1"           "ht1_column_title_1"            
## [11] "ht1_row_title_1"                "ht1_row_title_2"               
## [13] "ht1_dend_row_1"                 "ht1_dend_row_2"                
## [15] "ht1_dend_column_1"              "ht1_row_names_1"               
## [17] "ht1_row_names_2"                "ht1_column_names_1"            
## [19] "annotation_points_1"            "heatmap_ht2"                   
## [21] "ht2_heatmap_body_wrap"          "ht2_heatmap_body_1_1"          
## [23] "ht2_heatmap_body_1_2"           "ht2_heatmap_body_2_1"          
## [25] "ht2_heatmap_body_2_2"           "ht2_column_title_1"            
## [27] "ht2_dend_column_1"              "ht2_dend_column_2"             
## [29] "ht2_column_names_1"             "ht2_column_names_2"            
## [31] "annotation_type_1"              "annotation_type_2"             
## [33] "heatmap_heatmap_annotation_11"  "annotation_bar_1"              
## [35] "annotation_bar_2"               "global-column_title_top"       
## [37] "global_column_title"            "global-row_title_left"         
## [39] "global_row_title"               "global-heatmap_legend_right"   
## [41] "heatmap_legend"                 "global-annotation_legend_right"
## [43] "annotation_legend"

为了防止你记不住,作者提供了风格一致的名字:

  • decorate_heatmap_body()
  • decorate_annotation()
  • decorate_dend()
  • decorate_title()
  • decorate_dimnames()
  • decorate_row_names(), identical to decorate_dimnames(..., which = "row").
  • decorate_column_names(), identical to decorate_dimnames(..., which = "column").
  • decorate_row_dend(), identical to decorate_dend(..., which = "row").
  • decorate_column_dend(), identical to decorate_dend(..., which = "column").
  • decorate_row_title(), identical to decorate_title(..., which = "row").
  • decorate_column_title(), identical to decorate_title(..., which = "column")

一个例子:

ht_list = draw(ht_list, row_title = "Heatmap list", column_title = "Heatmap list"
    heatmap_legend_side = "right", annotation_legend_side = "left")

decorate_heatmap_body("ht1", {
    grid.text("outlier"1.5/102.5/4, default.units = "npc")
    grid.lines(c(0.50.5), c(01), gp = gpar(lty = 2, lwd = 2))
}, slice = 2)

decorate_column_dend("ht1", {
    tree = column_dend(ht_list)$ht1[[1]]
    ind = cutree(as.hclust(tree), k = 2)[order.dendrogram(tree)]

    first_index = function(l) which(l)[1]
    last_index = function(l) { x = which(l); x[length(x)] }
    x1 = c(first_index(ind == 1), first_index(ind == 2)) - 1
    x2 = c(last_index(ind == 1), last_index(ind == 2))
    grid.rect(x = x1/length(ind), width = (x2 - x1)/length(ind), just = "left",
        default.units = "npc", gp = gpar(fill = c("#FF000040""#00FF0040"), col = NA))
})

decorate_row_names("ht1", {
    grid.rect(gp = gpar(fill = "#FF000040"))
}, slice = 2)

decorate_row_title("ht1", {
    grid.rect(gp = gpar(fill = "#00FF0040"))
}, slice = 1)

decorate_annotation("points", {
    grid.lines(c(01), unit(c(00), "native"), gp = gpar(col = "red"))
})
plot of chunk unnamed-chunk-32

作者还提供了其他一些例子,就不一一介绍了

sessionInfo()
## R version 4.1.0 (2021-05-18)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19044)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=Chinese (Simplified)_China.936 
## [2] LC_CTYPE=Chinese (Simplified)_China.936   
## [3] LC_MONETARY=Chinese (Simplified)_China.936
## [4] LC_NUMERIC=C                              
## [5] LC_TIME=Chinese (Simplified)_China.936    
## 
## attached base packages:
## [1] grid      stats     graphics  grDevices utils     datasets  methods  
## [8] base     
## 
## other attached packages:
## [1] circlize_0.4.13      ComplexHeatmap_2.8.0
## 
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.7          cluster_2.1.2       knitr_1.33         
##  [4] magrittr_2.0.1      BiocGenerics_0.38.0 IRanges_2.26.0     
##  [7] doParallel_1.0.16   clue_0.3-59         colorspace_2.0-2   
## [10] rjson_0.2.20        foreach_1.5.1       highr_0.9          
## [13] stringr_1.4.0       tools_4.1.0         parallel_4.1.0     
## [16] xfun_0.25           png_0.1-7           iterators_1.0.13   
## [19] matrixStats_0.60.0  digest_0.6.27       crayon_1.4.1       
## [22] RColorBrewer_1.1-2  S4Vectors_0.30.0    GlobalOptions_0.1.2
## [25] codetools_0.2-18    shape_1.4.6         evaluate_0.14      
## [28] stringi_1.7.3       compiler_4.1.0      magick_2.7.3       
## [31] stats4_4.1.0        Cairo_1.5-12.2      GetoptLong_1.0.5


以上就是今天的内容,希望大家都能学会!


欢迎关注我的公众号:医学和生信笔记

医学和生信笔记 公众号主要分享:1.医学小知识、肛肠科小知识;2.R语言和Python相关的数据分析、可视化、机器学习等;3.生物信息学学习资料和自己的学习笔记!


往期精彩内容:

在VScode中使用R语言


R语言画dumbbell chart


超详细的R语言热图之complexheatmap系列2



您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存