Search code examples
rcomplexheatmap

R ComplexHeatmap with discrete values - show missing values in legend


I use the R package ComplexHeatmap to display my matrix with discrete values. These values range from 1-10, however, some values (e.g. 7, 8, 9) are missing. But still, I want them to be shown in the legend bar. Is this possible?

This is how far I got:

    library(ComplexHeatmap)
    
    discrete_mat = matrix(sample(1:10, 100, replace = TRUE), 10, 10)
    discrete_mat[discrete_mat==7]<-NA
    discrete_mat[discrete_mat==8]<-1
    discrete_mat[discrete_mat==9]<-1

    pal <- colorRampPalette(c("skyblue", "yellow", "orange", "darkred"))(10)
    colors = structure(pal, names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

    Heatmap(discrete_mat,
        name = "Legend", 
        col = colors,
        cluster_rows = FALSE, # turn off row clustering
        cluster_columns = FALSE
        )

Here an image of the result: ComplexHeatmap where the values for 7,8,9 are missing in the legend


Solution

  • Sort of a work-around, but I'd just make the legend manually

    Edit: no seed set in question so looks a bit different

    ht <- Heatmap(discrete_mat,
      col = colors,
      show_heatmap_legend = FALSE,
      cluster_rows = FALSE,
      cluster_columns = FALSE
    )
    
    leg <- Legend(
      title = "Legend",
      at = 1:10,
      labels = as.character(1:10),
      legend_gp = gpar(fill = pal)
    )
    
    draw(ht, heatmap_legend_list = leg)