2

I created a heatmap in R which is n*k in size, is it possible to extract the individual colors used for an ith element?

For example n=3 (columns) and k=50 (rows), n is an arbitrary level of severity and k represents a district in the UK.

I have the polygons for these districts and I want to create 3 separate maps based on the severity using the same colors from the overall heatmap as the fill for the polygons for consistency.

Thanks, Alan

1 Answers1

2

To understand how this works, I had to look into the code of pheatmap. Let's first generate a matrix:

A <- matrix(1:10, 2, 5)

The default palette is defined as

pal <- colorRampPalette(rev(RColorBrewer::brewer.pal(n = 7, name = "RdYlBu")))(100)

The idea is then to define break values and assign a color to each of the intervals defined by the breaks:

bks <- pheatmap:::generate_breaks(A, length(pal), center = F)
A2 <- pheatmap:::scale_colours(A, col=pal, breaks=bks)

Matrix A2 contains the colors associated to each cell of A:

A2
#          [,1]      [,2]      [,3]      [,4]      [,5]     
# [1,] "#4575B4" "#ABD0E4" "#F4FBD2" "#FEDF8F" "#EF6D48"
# [2,] "#77A6CE" "#E0F3F7" "#FEF4AF" "#FCA86B" "#D73027"

Finally, we can represent A with colors defined in A2 first with pheatmap, and also with image:

pheatmap(t(A[,5:1]),cluster_rows = F, cluster_cols = F)

With pheatmap

image(A, col=A2)

With image

Ref: Kolde, R. (2013). pheatmap: Pretty Heatmaps.

Vincent Guillemot
  • 3,394
  • 14
  • 21
  • If you changed `A <- matrix(rnorm(10), 2, 5)` This doesn't seem to work. Can you explain why? Is it due to the size of the values? – lamecicle Jan 07 '15 at 15:07
  • 1
    Can you try `image(matrix(1:10,2,5), col=A2)`? I think `image` is confused if `A` contains random values. – Vincent Guillemot Jan 07 '15 at 15:17
  • I also tried to fill `A` with random values, and I got in `A2` the correct colors attributed by `pheatmap`. I checked on [this site](http://hex-color.com/). – Vincent Guillemot Jan 07 '15 at 15:18
  • Thanks @Vincent, worked perfectly. Once I had the A2 dataset it was easy for me to cycle through the districts using the ith element of the contents of A2 as the fill of my polygon. Cheers. :) – Al OLoughlin Jan 07 '15 at 16:36