arvchi
arvchi

Reputation: 61

Pheatmap: Re-order leaves in dendogram

I have created a heatmap with a corresponding dendogram based on the hierarchical clustering, using the pheatmap package. Now, I want to change the order of the leaves in the dendogram. Preferably using the optimal leaves method. I have searched around but not found any solution on how to change the achieve this.

I would appreciate suggestions on how to change the order of the leaves, using the optimal leaves method.

Here's my example code with random data:

mat <- matrix(rgamma(1000, shape = 1) * 5, ncol = 50)
p <- pheatmap(mat, 
         clustering_distance_cols = "manhattan",
         cluster_cols=TRUE,
         cluster_rows=FALSE
         )

Upvotes: 3

Views: 2733

Answers (1)

Istrel
Istrel

Reputation: 2588

For "optimal leaf ordering" you can use order method from seriation library. pheatmap accepts clustering_callback argument. According to docs:

clustering_callback callback function to modify the clustering. Is called with two parameters: original hclust object and the matrix used for clustering. Must return a hclust object.

So you need to construct callback function which accepts hclust object and initial matrix and returns optimized hclust object.

Here is a code:

library(pheatmap)
library(seriation)

cl_cb <- function(hcl, mat){
    # Recalculate manhattan distances for reorder method
    dists <- dist(mat, method = "manhattan")

    # Perform reordering according to OLO method
    hclust_olo <- reorder(hcl, dists)
    return(hclust_olo)
}

mat <- matrix(rgamma(1000, shape = 1) * 5, ncol = 50)
p <- pheatmap(mat, 
         clustering_distance_cols = "manhattan",
         cluster_cols=TRUE,
         cluster_rows=FALSE,
         clustering_callback = cl_cb
         )

Upvotes: 4

Related Questions