r - Save heatmap.2 in variable and plot again -


i use heatmap.2 gplots make heatmap:

library(gplots) # fake data m = matrix(c(0,1,2,3), nrow=2, ncol=2) # make heatmap hm = heatmap.2(m) 

when 'heatmap.2' directly plot can output device. how can make plot again variable 'hm'? toy example, in real life have function generates , returns heatmap plot later.

there several alternatives, although none of them particularly elegant. depends on if variables used function available in plotting environment. heatmap.2 doesn't return proper "heatmap" object, although contains necessary information plotting graphics again. see str(hm) inspect object.

if variables available in environment, re-evaluate original plotting call:

library(gplots) # fake data (adjusted bit) set.seed(1) m = matrix(rnorm(100), nrow=10, ncol=10) # make heatmap hm = heatmap.2(m, col=rainbow(4))  # below fails if variables not available in global environment eval(hm$call) 

i assume won't case though, mentioned calling plot command inside function , think you're not using global variables. re-construct heatmap drawing call fields available in hm-object. problem original matrix not available, instead have re-organized $carpet-field. requires tinkering obtain original matrix, projection has been:

# hm2$carpet = t(m[hm2$rowind, hm2$colind]) 

at least in case when data matrix has not been scaled, below should work. add parameters according specific plotting call.

func <- function(mat){     h <- heatmap.2(mat, col=rainbow(4))     h }  # eval(hm2$call) not work, 'mat' not available hm2 <- func(m)  # here hm2$carpet = t(m[hm2$rowind, hm2$colind]) # finding projection can bit cumbersome: revrowind <- match(c(1:length(hm2$rowind)), hm2$rowind) revcolind <- match(c(1:length(hm2$colind)), hm2$colind) heatmap.2(t(hm2$carpet)[revrowind, revcolind], rowv=hm2$rowdendrogram, colv=hm2$coldendrogram, col=hm2$col) 

furthermore, think may able work way evaluating hm$call in function's environment. perhaps with-function useful.

you make mat available attaching global environment, think considered bad practice, eager use of attach can result in problems. notice in example every call func creates original plot.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -