iTranslated by AI
[Plot] Adding a legend title to pheatmap
When drawing heatmaps with the pheatmap package, there is no option to add a title to the color map (legend for values).
df <- iris[,1:4]
anno <- iris[,5, drop=FALSE]
rownames(df) <- rownames(anno) <- as.character(seq(nrow(df)))
pheatmap::pheatmap(mat = df, annotation_row = anno, show_rownames = F)

ComplexHeatmap
The ComplexHeatmap package also has a pheatmap() function, which can draw heatmaps similar to the pheatmap package. With pheatmap from ComplexHeatmap, you can specify the legend title using the name= argument.
ComplexHeatmap::pheatmap(
mat = df,
annotation_row = anno,
show_rownames = F,
name = "Score")

Another way is to use the heatmap_legend_param = argument. This allows for various adjustments to the legend style in addition to the title name.
ComplexHeatmap::pheatmap(
mat = df,
annotation_row = anno,
show_rownames = F,
heatmap_legend_param = list(title = "Score",
title_position = "leftcenter-rot",
labels = c("Low", "Median", "High"),
at = c(0,4,8),
legend_height = grid::unit(30,"mm"),
grid_width = grid::unit(3,"mm"),
labels_gp = gpar(col = "blue", font = 4),
border = "black")
)

For details, refer here:
https://jokergoo.github.io/ComplexHeatmap-reference/book/legends.html
Legend position
pheatmap::pheatmap() does not have a feature to change the legend's placement. In the case of ComplexHeatmap::pheatmap(), you can change it by creating a plot object and using the heatmap_legend_side = option within the draw() function.
In the following example, the plot data is passed to draw() using a pipe.
library(dplyr)
ComplexHeatmap::pheatmap(
mat = df,
annotation_row = anno,
show_rownames = F,
heatmap_legend_param = list(title = "Score",
title_position = "topcenter",
legend_direction = "horizontal"
)
) %>% ComplexHeatmap::draw(heatmap_legend_side = "bottom")

With ComplexHeatmap::Heatmap(), you can specify the position of each legend using the annotation_legend_side= and heatmap_legend_size= options in draw(), but the annotation_legend_side= option did not work with ComplexHeatmap::pheatmap().
Discussion