Search code examples
rheatmapgplots

How can I extract the matrix derived from a heatmap created with gplots after hierarchical clustering?


I am making a heatmap, but I can't assign the result in a variable to check the result before plotting. Rstudio plot it automatically. I would like to get the list of rownames in the order of the heatmap. I'am not sure if this is possible. I'am using this code:

hm <-    heatmap.2( assay(vsd)[ topVarGenes, ], scale="row", 
         trace="none", dendrogram="both", 
         col = colorRampPalette( rev(brewer.pal(9, "RdBu")) )(255),
         ColSideColors = c(Controle="gray", Col1.7G2="darkgreen", JG="blue", Mix="orange")[
           colData(vsd)$condition ] )

Solution

  • You can assign the plot to an object. The plot will still be drawn in the plot window, however, you'll also get a list with all the data for each plot element. Then you just need to extract the desired plot elements from the list. For example:

    library(gplots)
    
    p = heatmap.2(as.matrix(mtcars), dendrogram="both", scale="row")
    

    p is a list with all the elements of the plot.

    p # Outputs all the data in the list; lots of output to the console
    
    str(p) # Struture of p; also lots of output to the console
    
    names(p) # Names of all the list elements
    
    p$rowInd # Ordering of the data rows
    
    p$carpet # The heatmap values
    

    You'll see all the other values associated with the dendrogram and the heatmap if you explore the list elements.