I am working in R with the pheatmap library. I am creating heatmaps for different timepoints for the same population, so I want the legend scale to be fixed (from -2 to 2) for each heatmap so they can be easily compared. Then, values that are outside of that range would be set to the color of either -2 or 2.

I've tried to set a fixed range by using the legend_break and legend_labels options, but they only change the labels on the legend, not the actual scale limits themselves.
# Set Legend Limits
legend_breaks <- seq(-2, 2, length.out = 21)
legend_labels <- c("-2", rep("", 4), "-1", rep("", 4), "0",
rep("", 4), "1", rep("", 4), "2")
# Plot Heat Map
pheatmap(temp_m[,8:ncol(temp_m)],
scale="column",
annotation_colors = ann_colors,
color=colorRampPalette(c("navy", "white", "red"))(20),
main="Temp",
cluster_rows = FALSE,
cluster_cols = FALSE,
show_rownames = FALSE,
gaps_row = gaps,
angle_col = 90,
border_color = "grey",
legend_breaks = legend_breaks,
legend_labels = legend_labels,
annotation_row = rows,
# annotation_legend = TRUE,
# annotation_names_row = TRUE,
fontsize=11, cellwidth=10, cellheight=10)
I just had a solution about how to get a same scale in the legend across different heatmaps made by pheatmap package in R.
In your case, you can try add:
If you scale the legend from -10 to 10, and the number of color increase from 20 to 50, the sequence of numbers in breaks could be have interval of 0.4 (20/50 = 0.4). The point is that the number of the sequence number in breaks is same to the number of the color.