Search code examples
rggplot2heatmappheatmap

How to create heatmap with reverse color legend in r?


I would like to generate a heatmap in r(e.g using pheatmap package or other packages), where the smaller the value is, the darker the color is. Use only one color, with light and dark.

Example code:
X = matrix(runif(1000,0,1),100,10)
rownames(X) = paste("Var", 1:100, sep = "")
colnames(X) = paste("Var", 1:10, sep = "")

Solution

  • You could use the Blues palette from RColorBrewer which could be from dark blue to light blue in pheatmap like this:

    X = matrix(runif(1000,0,1),100,10)
    rownames(X) = paste("Var", 1:100, sep = "")
    colnames(X) = paste("Var", 1:10, sep = "")
    library(pheatmap)
    library(RColorBrewer)
    pheatmap(X, color = rev(brewer.pal(9, "Blues")))
    

    Created on 2023-02-21 with reprex v2.0.2


    As @DaveArmstrong mentioned in the comments, you could use a colorRampPalette to make it look more continuous like this:

    library(pheatmap)
    library(RColorBrewer)
    pheatmap(X, color=colorRampPalette(rev(brewer.pal(9, "Blues")))(100))
    

    Created on 2023-02-21 with reprex v2.0.2