How to change row order in heatmap?

Is it possible to change the row order in heatmap?
I created a heatmap using similar code like the one below:

scaledDT<- as.matrix(head(mtcars, 6)) 

pheatmap::pheatmap(scaledDT, treeheight_row = 0, treeheight_col = 0, cluster_row=TRUE)

The row order in the heatmap is "Hornet Sportabout", "Hornemt 4 Drive", "Valiant", "Datsun 710", "Mazda RX4", "Mazda RX4 Wag", if want the heatmap displays reverse row name order like "Mazda RX4 Wag", "Mazda RX4", "Datsun 710", "Valiant", "Hornemt 4 Drive", "Hornet Sportabout".
How can achieve it? Thank you.

It's possible with limitations.

Since you are using cluster_row = TRUE, the order is largely determined by the clustering. So you can't choose an order yourself, as it could be incompatible with the clustering.

However, you can provide a function that will be called after clustering. See the clustering_callback argument.

So in a very forceful example:

callback_rev <- function(hc, mat){
  hc$order <- rev(hc$order)
pheatmap::pheatmap(scaledDT, cluster_row=TRUE, clustering_callback = callback_rev)

but you probably want to write a more flexible function, see the Examples section of ?pheatmap to see a use of {densort}.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.