Search code examples
rcomplexheatmap

ComplexHeatmap, cannot create horizontal legend


Hi I'm using the ComplexHeatmap package and followed their vignette however for some reason I cannot seem to force the legend to become horizontal. So for example here is an example,

set.seed(123)
library(ComplexHeatmap)
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)

ha_column = HeatmapAnnotation(df = data.frame(type1 = c(rep("a", 5), rep("b", 5))),
                              col = list(type1 = c("a" =  "red", "b" = "blue")), 
                              annotation_legend_param = list(type1 = list( 
                                            title_gp = gpar(fontsize = 16), 
                                            legend_direction = "horizontal", labels_gp = gpar(fontsize = 8)))
                              )



ht1 = Heatmap(mat, name = "ht1", column_title = "Heatmap 1", top_annotation = ha_column)
draw(ht1, heatmap_legend_side = "right")

so despite add in legend_direction = "horizontal" I still keep getting this here, enter image description here


Solution

  • If you need to plot the heatmap legend horizontally and at the bottom of the heatmap, you can use this solution:

    ht1 = Heatmap(mat, name = "ht1", column_title = "Heatmap 1", top_annotation = ha_column, 
                  heatmap_legend_param = list(
                                          legend_direction = "horizontal", 
                                          legend_width = unit(5, "cm")
                                         )
                  )
    draw(ht1, heatmap_legend_side = "bottom")
    

    enter image description here

    Otherwise, if you need to draw your (discrete) annotation legend horizontally and at the top of the heatmap, you can use nrow=1 in annotation_legend_param:

    ha_column = HeatmapAnnotation(df = data.frame(type1 = c(rep("a", 5), rep("b", 5))),
                                  col = list(type1 = c("a" =  "red", "b" = "blue")), 
                                  annotation_legend_param = list(
                                                type1 = list( 
                                                  title_gp = gpar(fontsize = 16), 
                                                  labels_gp = gpar(fontsize = 8), 
                                                  nrow=1)))
    
    
    ht1 = Heatmap(mat, name = "ht1", column_title = "Heatmap 1", top_annotation = ha_column)
    draw(ht1, annotation_legend_side = "top")
    

    enter image description here