0

When plotting a heatmap in R from a given matrix, it automatically reorders the rows and columns so the visualization is easier.

I was wondering how it does that so that I can reorder the actual data frame itself with the numbers. (so the matrix with the numbers is reordered)

I hope this makes sense.

Thanks

Grint
  • 101
  • 2
  • 1
    It's easier to help you and give specific advice if you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data and the function call you are using. I assume you've at least read the `?heatmap` help page to see read how reordering is done. – MrFlick Mar 27 '17 at 15:04
  • which heatmap function are you currently using?? In general you can 'scale' your data by row or column or even both. That's how the function reorder your data. But you can treat your data using Pearson correlation or euclidean – Fábio Mar 27 '17 at 15:06
  • Did you solve the problem? – Joe Jul 30 '19 at 14:37

2 Answers2

0

You can get the clustered orders by assigning your heatmap to an object rather than plotting it. Let's try with some random data:

set.seed(111)
mat <- matrix(rnorm(40), nrow=4)
h <- heatmap(mat)

Now the orders are stored in rowInd and colInd.

> h$rowInd
[1] 3 2 4 1

So, to get the reordered matrix, use indices with the original matrix:

mat[h$rowInd, h$colInd]

Note: you can use for example mat[rev(h$rowInd), ] if you want to reverse the order of the rows.

Joe
  • 8,073
  • 1
  • 52
  • 58
0

Using the heatmap.2 function in gplots package, fortunately this can be done more easily. First load in some test data:

my.image <-
structure(c(0.284887135194186, 0.0266252817250525, 0.348431746937973, 
0.746492464670314, 0.267235059081902, 0.0209642747046111, 0.378676942016667, 
0.607990837304665, 0.312847060269367, 0.612395191587952, 0.483024535963144, 
0.564162902506238, 0.128115012083734, 0.548085047655703, 0.614939304016718, 
0.51253667320726, 0.591278116015954, 0.395201893060755, 0.682934039875973, 
0.416956130236154, 0.677632422556141, 0.385639902518959, 0.692257324851365, 
0.358990284723972, 0.224435642972774, 0.376108601670825, 0.717444067668913, 
0.308920663224123, 0.149392034309146, 0.399379225875787, 0.158378066789988, 
0.0536693928847938, 0.049487973904056, 0.54274177846382, 0.0398607307385965
), .Dim = c(7L, 5L), .Dimnames = list(c("row1", "row2", "row3", 
"row4", "row5", "row6", "row7"), c("col1", "col2", "col3", "col4", 
"col5")))    

Then plot the heatmap, preserving the row and column order:

library(gplots)
heatmap.2(my.image, density.info="none", trace="none", dendrogram='none', 
     Rowv=FALSE, Colv=FALSE)

The image looks like this:

enter image description here

This article by Sebastian Rashka is also very helpful for producing heatmaps that actually look good: http://sebastianraschka.com/Articles/heatmaps_in_r.html

mysteRious
  • 4,102
  • 2
  • 16
  • 36