在 R 中使热图看起来更专业

Make Heatmap Look More Professional in R

我可以在 R 中构建非常基本的绘图,但我试图让我的热图看起来更专业,但我不确定如何去做。我有一个数据框 df,包含 11 个变量的 11 个观察值:

> dput(df)
structure(list(`0` = c(6.08, 7.91, 5.14, 2.23, 0.72, 0.19, 0.04, 
0.01, 0, 0, 0), `1` = c(9.12, 11.86, 7.71, 3.34, 1.09, 0.28, 
0.06, 0.01, 0, 0, 0), `2` = c(6.84, 8.89, 5.78, 2.5, 0.81, 0.21, 
0.05, 0.01, 0, 0, 0), `3` = c(3.42, 4.45, 2.89, 1.25, 0.41, 0.11, 
0.02, 0, 0, 0, 0), `4` = c(1.28, 1.67, 1.08, 0.47, 0.15, 0.04, 
0.01, 0, 0, 0, 0), `5` = c(0.38, 0.5, 0.33, 0.14, 0.05, 0.01, 
0, 0, 0, 0, 0), `6` = c(0.1, 0.13, 0.08, 0.04, 0.01, 0, 0, 0, 
0, 0, 0), `7` = c(0.02, 0.03, 0.02, 0.01, 0, 0, 0, 0, 0, 0, 0
), `8` = c(0, 0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0), `9` = c(0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0), `10+` = c(0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0)), row.names = c("0", "1", "2", "3", "4", "5", "6", "7", 
"8", "9", "10+"), class = "data.frame")

所以我将 df 转换为矩阵以获得热图:

heatmap(data.matrix(df), Rowv=NA, Colv=NA, col = heat.colors(256), scale="column", margins=c(5,10))

剧情是这样的:

我不确定如何:

  1. 更改行和列的键的位置。我希望它们都从左上角的 0 开始,并且行和列都继续上升直到 10+
  2. 我还想要更精细的颜色。现在你不能通过看颜色来判断值的差异...

来自 base R 的 heatmap 是否适合这个库?我查了几个例子,我不确定是否有更好的库来实现我想要的。

有几个库提供热图功能。 IMO 基础 heatmapgplots::heatmap.2 老化不佳,不再是最佳选择。 ggplot2::geom_tilepheatmapComplexHeatmap.

有 3 个好的可能性

示例数据

假设我们有一个矩阵

dta <- matrix(rnorm(25), nrow=5)
rownames(dta) <- letters[1:5]
colnames(dta) <- LETTERS[1:5]

ggplot2::geom_tile

ggplot2 版本要求您的数据是整齐的数据框,因此我们可以使用 tidyr::pivot_longer().

转换矩阵
dta %>%
  as_tibble(rownames = "myrows") %>%
  pivot_longer(cols = -myrows, names_to = "mycols", values_to = "level") %>%
  ggplot() +
  geom_tile(aes(x=myrows, y=mycols, fill = level))

作弊图

pheatmap 包非常擅长生成现代热图。它需要一个矩阵作为输入。它可以对行和列进行聚类并制作树状图,这通常是所需的功能。它还可以缩放行和列(有效地绘制 Z-score)。

pheatmap::pheatmap(dta,
                   scale = "none",
                   cluster_rows = FALSE,
                   cluster_cols = FALSE)

注意行和列的位置与ggplot不同。您可以查看允许进行一些有用的自定义的选项。例如,如果我们的行在别处定义了 类。

ann_df <- data.frame(row.names = rownames(dta),
                     classification = rep(c("first", "second"), times = c(2,3)))
pheatmap::pheatmap(dta,
                   scale = "none",
                   cluster_rows = FALSE,
                   cluster_cols = FALSE,
                   annotation_row = ann_df,
                   gaps_row = c(2))

色阶

让你的热图看起来很专业的一个重要方面是色标。在 ggplot 上,你应该查看 scale_fill_gradient2().

在 pheatmap 上,您可以尝试 color 的这些设置作为起点(请参阅这些函数的文档):

color = scales::div_gradient_pal(low = "navy",
  mid = "green",
  high="yellow")(seq(0,1,
    length.out = max(dta))),

color = colorRampPalette(RColorBrewer::brewer.pal(n = 9,
      name = "Blues"))(max(dta)),

color = viridisLite::plasma(max(dta)),

复杂热图

最后,最近获得成功的一个包是ComplexHeatmap。它基于 pheatmap 但提供了许多附加选项。请参阅 zx8754 评论中的 the link 以获取包含大量示例的详细书籍。