Hello,

I'm trying to write a function that creates and decorates a heatmap based on a given input data. The code works well, but not when it's written within a function. I'll simplify what I mean by using a very simple example from one of the vignettes of the package:

library(ComplexHeatmap)

**## Generate data**

mat = matrix(rnorm(80, 2), 8, 10)

mat = rbind(mat, matrix(rnorm(40, -2), 4, 10))

rownames(mat) = paste0("R", 1:12)

colnames(mat) = paste0("C", 1:10)

**## Create and decorate the heatmap: this works well**

Heatmap(mat, name = "ht1", km = 2)

decorate_column_dend("ht1", {

tree = column_dend(ht1)

ind = cutree(as.hclust(tree), k = 2)[order.dendrogram(tree)]

first_index = function(l) which(l)[1]

last_index = function(l) { x = which(l); x[length(x)] }

x1 = c(first_index(ind == 1), first_index(ind == 2)) - 1

x2 = c(last_index(ind == 1), last_index(ind == 2))

grid.rect(x = x1/length(ind), width = (x2 - x1)/length(ind), just = "left",

default.units = "npc", gp = gpar(fill = c("#FF000040", "#00FF0040"), col = NA))

})

**## Create and decorate heatmap inside of a function: ERROR!**

do_heatmap = function (mat) {

Heatmap(mat, name = "ht1", km = 2)

decorate_column_dend("ht1", {

tree = column_dend(ht1)

ind = cutree(as.hclust(tree), k = 2)[order.dendrogram(tree)]

first_index = function(l) which(l)[1]

last_index = function(l) { x = which(l); x[length(x)] }

x1 = c(first_index(ind == 1), first_index(ind == 2)) - 1

x2 = c(last_index(ind == 1), last_index(ind == 2))

grid.rect(x = x1/length(ind), width = (x2 - x1)/length(ind), just = "left",

default.units = "npc", gp = gpar(fill = c("#FF000040", "#00FF0040"), col = NA))

})

}

**## Test the function**

do_heatmap(mat)

**Error in grid.Call.graphics(C_downviewport, name$name, strict) :
Viewport 'ht1_dend_column' was not found**

Any idea about how to solve this??

Thanks very much in advance,

Best wishes,

Andrea