Take the following code:
heatmap(data.matrix(signals),col=colors,breaks=breaks,scale="none",Colv=NA,labRow=NA)
How can I extract, pre-calculate or re-calculate the order of the rows in the heatmap produced? Is there a way to inject the output of hclust(dist(signals))
into the heatmap function?
I believe this post might be useful:
How does R heatmap order rows by default?
Take the following matrix for example:
You can override the order of the rows and columns with the parameters
Rowv
andColv
. You can override the order with these as dendrograms. For instance, you can calculate an order using the functionhclust
, then pass that toheatmap
as a dendrogram:Gives:
Hclust heatmap
The default heatmap function uses one additional step, however, through the parameter
reorderfun = function(d, w) reorder(d, w)
, which reorders the dendrogram as much as possible bases on row/column mean. you can reproduce the default order with this additional step. So to get the same ordering asheatmap
, you can do:Which gives the same output as simply
heatmap(m)
:Default heatmap
In this example the columns happen to not get reordered, but the rows do. Finally, to simply retrieve the order you can assign the heatmap to a variable and get the output.
pheatmap will allow you to specify the method that it uses to do the clustering, accepting the same arguments as hclust.
Thanks for the feedback, Jesse and Paolo. I wrote the following ordering function which will hopefully be useful to others:
I agree with Jesse. For your problem take a look at the
Rowv
,distfun
andhclustfun
arguments of the heatmap function. For more choices the functionsheatmap.2
in thegplots
package,heatmap_plus
in theHeatplus
package andpheatmap
in thepheatmap
package could be of some use.There are a variety of options. If you run
?heatmap
you'll see the various parameters you can tweak. Maybe the easiest is to setRowv=NA
which should suppress row reordering, and then pass in the matrix with the rows already in the order you want. But you can also manually provide a clustering function, or dendrograms, viaRowv
andhclustfun
etc...