Search code examples
rhierarchical-clusteringpheatmapheatmaply

Using heatmaply dendrogram sorting in pheatmap


Is there a way of using the dendrogram clustering method used in the heatmaply package and to apply it to a heatmap produced by the pheatmap package? Basically the opposite to what was asked here: Clustering in pheatmap and heatmaply R packages

I usually see better clustering of my data when I use heatmaply over pheatmap. However, I do not always want to use an interactive plot. The heatmaply::ggheatmap function does not work properly for me since I have have col_side_colors and the annotation gets in the way of the dendrogram. It just looks very messy. So I use pheatmap instead.

Maybe someone can help with my question. Thanks!


Solution

  • library(pheatmap)
    library(heatmaply)
    library(seriation)
    library(dendextend)
    
    # A dataset    
    x <- scale(mtcars)
    
    # Interactive heatmap
    p <- heatmaply(x)
    print(p)
    
    # The dendrogram for rows
    dst <- dist(x)
    hc_row <- hclust(dst)
    row_dend <- as.dendrogram(hc_row)
    row_dend <- seriate_dendrogram(row_dend, dst, method="OLO")
    
    # The dendrogram for columns
    dst <- dist(t(x))
    hc_row <- hclust(dst)
    col_dend <- as.dendrogram(hc_row)
    col_dend <- seriate_dendrogram(col_dend, dst, method="OLO")
    col_dend <- rotate(col_dend, order = rev(labels(dst)[get_order(as.hclust(col_dend))]))
    
    # The pheatmap with the same clustering of heatmaply
    pheatmap(x, cluster_rows=as.hclust(row_dend), cluster_cols=as.hclust(col_dend))
    

    The output of heatmaply enter image description here

    and the output of pheatmap enter image description here