如何在 R 中创建带有自定义文本的交互式热图?

How to create an interactive heatmaply plot with custom text in R?

我有一个数据集,我在其中绘制热图来比较 7 个组。我还在数据 2 列中包含我想作为悬停文本包含在交互式热图中的信息。

我的数据是我要比较的 7 列组,以及我要添加到绘图中的 2 列悬停文本信息。这些行是我希望比较组间重要性的对数 p 值。

目前我正在尝试使用 heatmaply 来绘制它,但是我在设置自定义文本时遇到了问题 - 有没有办法将数据列设置到 heatmaply()custom_text 中=]?我找不到任何专门执行此操作的示例。

输入示例数据:

df <- structure(list(Group1 = c(9.420318259, 5.801092847, 
4.890727291, 4.589825753, 4.836092781), Group2 = c(14.57805564, 
8.798453748, 7.982599836, 7.951599435, 10.81418654), Group3 = c(14.49131554, 
7.975284646, 8.258878348, 7.922657108, 13.3205827), Group4 = c(11.44447147, 
6.208332721, 6.529806574, 4.882623805, 10.69676399), Group5 = c(22.86835197, 
10.94297858, 7.197041788, 9.237584441, 12.70083108), Group6 = c(10.62687539, 
6.458410247, 7.461916094, 6.308454021, 12.39464562), Group7 = c(11.09404106, 
6.420303272, 6.821000583, 5.0727153, 11.13903127), Gene_Overlap = c(37L, 
14L, 14L, 13L, 22L), Mean_GB_Score = c(0.798, 0.788, 0.81, 0.879, 
0.805)), row.names = c("Cardiac Hypertrophy", 
"Cellular Effects of Adrenaline", "Metastasis Signaling", 
"Hormone Signaling", "Estrogen Receptor Signaling"
), class = "data.frame")

我尝试使用的代码:

groups <- as.matrix(df[,1:7])

heatmaply(groups, custom_hovertext = df[[Gene_Overlap]], scale_fill_gradient_fun = ggplot2::scale_fill_gradient2(
  low = "pink", 
  high = "red"))

custom_hovertext 参数的描述中,您可以看到它应该是一个与输入具有相同维度的矩阵,即具有 5 行和 7 列的矩阵。

所以首先我们需要构建这样的矩阵:

library(dplyr)

labels <- 
  df %>% 
  mutate(label = paste(
    "Gene Overlap:", Gene_Overlap,
    "\nMean_GB_Score:", Mean_GB_Score
  )) %>% 
  # this writes contens of the new `label` column
  # in place of all the Group columns
  transmute(across(Group1:Group7, ~label)) %>% 
  as.matrix()

然后我们可以在heatmaply

中使用它
library(heatmaply)
heatmaply(
  groups,
  custom_hovertext = labels,
  scale_fill_gradient_fun = ggplot2::scale_fill_gradient2(low = "pink", high = "red")
)