R ComplexHeatmap with discrete values - show missing values in legend

81 Views Asked by At

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

2

There are 2 best solutions below

0
knitz3 On BEST ANSWER

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)

2
Martin On

I found the solution here: https://stackoverflow.com/a/70657873/23382058


    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 = pal,
            cluster_rows = FALSE, # turn off row clustering
            cluster_columns = FALSE,
            
            heatmap_legend_param = list(
              #at = seq(1, 10, by = 1),  #wär gleich: at = 1:10,       
              at = 1:10,
              legend_gp = gpar(fill = 1:10, fontsize = 2),
              color_bar = "discrete"
              ),
            )