[R] Heatmap Colors

Achim Zeileis Achim.Zeileis at uibk.ac.at
Sat Sep 29 10:54:11 CEST 2012


On Fri, 28 Sep 2012, David Winsemius wrote:

>
> On Sep 28, 2012, at 4:52 PM, David Winsemius wrote:
>
>>
>> On Sep 28, 2012, at 3:16 PM, Nick Fankhauser wrote:
>>
>>> Hello R-Users!
>>>
>>> I'm using a heatmap to visualize a matrix of values between -1 and 3.
>>> How can I set the colors so that white is zero, below zero is blue of increasing intensity towards -1 and above zero is red of increasing intensity towards red?
>>>
>>> I tried like this (using the marray and gplots packages from bioconductor):
>>> mcol <- maPalette(low="blue", mid="white", high="red",k=100)
>>> heatmap.2(my_matrix, col=mcol)
>>>
>>> But white does not correspond to zero, because the value distribution is not symmetrical, so that zero is not in the middle.
>>> Is it somehow possible to create a color palette with white centered at zero?
>>
>> The way you stated it at the beginning, I thought you should want the palette centered at 1 rather than 0:
>
> Oopps ... should have the number of breaks match the number of colors:
>
> test <- seq(-1,3, len=20)
> shift.BR <- colorRamp(c("blue","white", "red"), bias=2)((1:20)/20)
> tpal <- rgb(shift.BR, maxColorValue=255)
> barplot(test,col = tpal)
>>

The other option, instead of adjusting the palette, is to adjust the 
breaks used by heatmap.2. Furthermore, I would recommend not to use a 
palette with the fully saturated colors you get by the approach above. 
RColorBrewer and colorspace provide better perceptually-based palettes. 
Here, I use diverge_hcl() from colorspace that gives matching perceptual 
weight to values of -1 and plus 1.

## data
set.seed(1)
my_matrix <- matrix(rbeta(400, 1, 2) * 4 - 1, ncol = 20)

## color and breaks
br <- seq(-3, 3, by = 0.25)
cl <- diverge_hcl(length(br) - 1, power = 1)

## heatmap
heatmap.2(my_matrix, col = cl, breaks = br)

> -- 
>
> David Winsemius, MD
> Alameda, CA, USA
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list