Error in printing values within complex heatmap

Viewed 21

I am trying to use the ComplexHeatmap R package to generate heatmaps and also print the values.

NES_final is a list of list containing expt at first level and scenario at second level. Within each expt I need to create a combined heatmap of all scenario.

The heatmap is created as expected, but while printing only the last value of scenario in each expt gets printed for all heatmaps within that expt.

Test data:

NES_final = list("expt1" = list("scenario1" = matrix(rnorm(36), nrow=3, ncol=3),
                                "scenario2" = matrix(rnorm(36), nrow=3, ncol=3),
                                "scenario3" = matrix(rnorm(36), nrow=3, ncol=3)),
                 "expt2" = list("scenario1" = matrix(rnorm(36), nrow=3, ncol=3),
                                "scenario2" = matrix(rnorm(36), nrow=3, ncol=3),
                                "scenario3" = matrix(rnorm(36), nrow=3, ncol=3)),
                 "expt3" = list("scenario1" = matrix(rnorm(36), nrow=3, ncol=3),
                                "scenario2" = matrix(rnorm(36), nrow=3, ncol=3),
                                "scenario3" = matrix(rnorm(36), nrow=3, ncol=3)))

Code:

    for(expt in names(NES_final)){
      NES <- NES_final[[expt]]      
      heatMap <- NULL
      for(scenario in names(NES)){       
        heatMap <- heatMap + Heatmap(NES[[scenario]],
                                     cluster_rows = FALSE,
                                     cluster_columns = FALSE,
                                     name = scenario,
                                     column_title = scenario,
                                     show_heatmap_legend = TRUE,
                                     cell_fun =  function(j, i, x, y, width, height, fill){
                                       grid.text(scenario, x, y, gp = gpar(fontsize = 2))
                                     }
                                     )
      }
      
      svglite(paste0("/Analysis_1/Heatmap_", expt, ".svg"), width = length(NES) * 25, height = 6)
      draw(heatMap, column_title = expt)
      dev.off()
    }
1 Answers

I was able to find a solution using the lapply function instead of the for loop for scenario.

heatMap <- lapply(names(NES), function(scenario){
         Heatmap(NES[[scenario]],
              cluster_rows = TRUE,
              cluster_columns = FALSE,
              name = scenario,
              column_title = scenario,
              show_heatmap_legend = FALSE,
              cell_fun =  function(j, i, x, y, width, height, fill){
                grid.text(scenario, x, y, gp = gpar(fontsize = 5))
              } ) })  }
 
  heatMap <- Reduce("+", heatMap)
  draw(heatMap, column_title = expt, padding = unit(c(0.5, 0.5, 0.5, 15), "cm"))
Related