如何在R中的距离矩阵旁边绘制树状图?

时间:2020-06-26 17:16:40

标签: r ggplot2 heatmap gplots

我正在寻找一种有效的方法来绘制从数据中获得的树状图,但要与相应的距离矩阵一起而不是原始数据。我一直好奇如何用不同的论文来展示这一点,似乎他们所做的只是将热图和树状图分别绘制出来,并在图像编辑软件中进行处理。希望以下代码能使我明白自己想要的。 假设我生成以下数据,并使用Pearson的相关性作为距离度量并使用完整的链接进行聚类:

library(gplots)
set.seed(2)
x <- matrix(rnorm(100), nrow = 5)
dist.fn <- function(x) as.dist(1-cor(t(x)))
hclust.com <- function(x) hclust(x, method="complete")
h.ori <- heatmap.2(x, trace="none", distfun=dist.fn, hclustfun=hclust.com,dendrogram = "row",main = "Fig1")
h.ori$rowInd
# 1 3 5 4 2

enter image description here

现在我可以按图1的树状图绘制相应的距离矩阵,以其行和列排序:

colfunc <- colorRampPalette(c("red", "white", "yellow")) #not really necessary
dmat <- cor(t(x))[h.ori$rowInd,h.ori$rowInd]
heatmap.2(dmat,Rowv = NULL,Colv = "Rowv",scale = 'none', 
          dendrogram='none',trace = 'none',density.info="none",
          labRow = h.ori$rowInd, labCol = h.ori$rowInd,
          col=colfunc(20))

enter image description here

这是我的问题:如何将图1中绘制的树状图添加到图2中的树状图上(最好沿列和行)?目的是查看由树状图生成的聚类,对于Block模型,这将是一种可视化的好方法。 还有一个附带的问题,我知道如何使用 ggplot2 库(即 geom_tile())绘制热图。有没有一种方法可以使用 ggplot2 做我上面想要的事情?

1 个答案:

答案 0 :(得分:2)

关于在ggplot2中执行此操作;我在某个时候编写了一个函数来帮助解决这个问题,尽管它并非没有缺陷。它使用hclust对象,并使用该对象绘制树状图作为轴向导。首先,我们将从以前的热图中获取树状图。

library(gplots)
#> Warning: package 'gplots' was built under R version 4.0.2
#> 
#> Attaching package: 'gplots'
#> The following object is masked from 'package:stats':
#> 
#>     lowess
library(ggplot2)
library(ggh4x) #devtools::install_github("teunbrand/ggh4x")

set.seed(2)
x <- matrix(rnorm(100), nrow = 5)
dist.fn <- function(x) as.dist(1-cor(t(x)))
hclust.com <- function(x) hclust(x, method="complete")
h.ori <- heatmap.2(x, trace="none", distfun=dist.fn, hclustfun=hclust.com,dendrogram = "row",main = "Fig1")
h.ori$rowInd
#> [1] 1 3 5 4 2

然后,将其格式化为hclust对象,然后将其放入秤。比例尺(理论上)应根据聚类自动对变量进行排序。

我只是在图的每一侧添加树状图,所以您可以选择真正想要的树状图。

# Plot prep: making the distance and hclust objects
clust <- as.hclust(h.ori$rowDendrogram)
df <- reshape2::melt(cor(t(x)))

ggplot(df, aes(Var1, Var2, fill = value)) +
  geom_raster() +
  scale_fill_gradient2(low = "red", mid = "white", high = "yellow")+
  scale_x_dendrogram(hclust = clust) +
  scale_y_dendrogram(hclust = clust) +
  guides(
    x.sec = guide_dendro(dendro = ggdendro::dendro_data(clust), position = "top"),
    y.sec = guide_dendro(dendro = ggdendro::dendro_data(clust), position = "right")
  ) +
  coord_equal()

要注意的是,对标签的控制还没有很好。如果您在使用该功能时遇到任何麻烦,请告诉我,以便我改善它。

祝你好运!