Search code examples
rpheatmap

Keeping the pheatmap color range the same for different heat maps


I have the following code to make two different pheatmaps representing correlation matrices.

A1 <- c(1,2,3,4)
B1 <- c(2,4,3,1)
C1 <- c(2,4,3,5)
D1 <- c(2,3,1,4)
E1 <- c(2,1,4,5)
Gene <- c(1,2,3,4)
df1 <- data.frame(Gene, A1, B1, C1, D1, E1)

CorMatrix1 <- cor(df1[, c("A1","B1","C1","D1","E1")])
CorMatrix1

pheatmap(CorMatrix1)

A2 <- c(2,5,6,4)
B2 <- c(4,8,9,3)
C2 <- c(5,7,8,1)
D2 <- c(1,2,6,4)
E2 <- c(3,7,5,4)
Gene <- c(1,2,3,4)
df2 <- data.frame(Gene, A2, B2, C2, D2, E2)

CorMatrix2 <- cor(df2[, c("A2","B2","C2","D2","E2")])
CorMatrix2

pheatmap(CorMatrix2)

My question is simple, how can I manipulate the pheatmap color scales so that they are the same for both pheatmaps? For example, how can make the color scales on both pheatmaps to go from -0.5 to 1?


Solution

  • Consider setting your own range of the legend, including the interval for which the color should change.

    # load package for color range   
    library(RColorBrewer)
    
    # define range (e.g., -0.5 to 1) and step size (e.g., 0.2)
    breaksList = seq(-0.5, 1, by = 0.2)
    
    # plot matrix1 with new range
    pheatmap(CorMatrix1,
    color = colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(length(breaksList)),
    breaks = breaksList)
    
    # plot matrix2 with new range
    pheatmap(CorMatrix2,
    color = colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(length(breaksList)),
    breaks = breaksList)