set color scale for heatmap

20,294

The command redgreen(50) is independent of your actual values and returns a vector of 50 colors. You can use this color vector and extract a subset of it to adapt it to you second matrix.

An example:

set.seed(1)
r.matrix <- matrix(runif(16, -1, 1), 4, 4)
r1.matrix <- r.matrix / 5

The values in matrix r1.matrix are one fifth of the values in r.matrix.

Now, the color vectors can be created in the following way:

library(gplots) 

rg <- redgreen(50)      # the original color vector

# range of values in first matrix around median
r1 <- range(r.matrix) - median(r.matrix)
# range of values in second matrix around median
r2 <- range(r1.matrix) - median(r1.matrix)
# relative distances to median of second compared to first matrix
prop <- r1 / r2

# center of colcor vector
cent <- length(rg) / 2 + 0.5

# calculate indices of shorter color vector for the second matrix
ind <- cent / prop
idx <- round(cent - c(1, -1) * ind)

# new color vector
rg_new <- rg[Reduce(seq, idx)]

Use these vectors to color the heatmaps:

heatmap(r.matrix, Colv = NA, col = rg)

enter image description here

heatmap(r1.matrix, Colv = NA, col = rg_new)

enter image description here

The range of colors in the second heatmap is smaller than the range in the first heatmap.

Share:
20,294
user2783615
Author by

user2783615

Updated on January 28, 2020

Comments

  • user2783615
    user2783615 over 4 years

    I am trying to compare data using heatmaps. I want to set the color scale to be the same for all of them. for example, all on the scale for values -0.5 to 0.5;

    I have been using gplots redgreen(50). but the color intensities are rescaled on different sets of data.

    for example: my r.matrix may range from -1 to +1; and my r1.matrix may range from -0.2 to +0.2. by plotting the two heatmap, if putting on the same color scale, I would expect the color for r1.matrix be much dimmer

    hm <- heatmap(r.matrix, Colv = NA, col = redgreen(50))
    hm1 <- heatmap(r1.matrix, Colv = NA, col = redgreen(50))
    

    The color scale will span across the data range, so with same redgreen(50) it will be same red or green for data ranging from -1 to +1 and for data ranging from -.2 to +.2. the reason to let the color span across [-1,1] on data ranging [-.2, .2] is to be able to visualize the difference in data, without looking into or knowing the data range -- an exploratory step.