Robert Robert - 1 year ago 59
R Question

Extract a matrix of color values from a heatmap or the underlying data

Here is a a matrix of relative weights:

weightmat <- matrix(c(0,3,6,4,0,5,7,2,0), nrow = 3, ncol = 3)

which I can use to produce a heatmap graphic using a number of dedicated methods, for example this one from plotrix:

color2D.matplot(weightmat, extremes = c("white", "red"))

All well and good, but what I would like to do now is return a matrix of the color values used in the heatmap so that I can use these to express weights in other graphical outputs, such as networks.
The output I am after, based on the above example, looks like this:

weightcol <- matrix(c("#FFFFFF","#FF9292","#FF2424","#FF6D6D","#FFFFFF","#FF4949","#FF0000", "#FFB6B6", "#FFFFFF"), nrow = 3, ncol = 3)

I have been tackling this so far by generating heatmaps with various dedicated functions (ggplot, plotrix etc) and trying to dissect the underlying data from the output, or else reproduce their calculations. However, I have found these data hard to access and wonder if someone can offer me a solution to bridge this gap.
Thank you in advance.

Answer Source

I am not sure you can extract the values from the color2D.matplot object, but from looking at the documentation, it seems that the function color.scale is used. You can find your values with:



     [,1]        [,2]        [,3]       
[1,] "#FFFFFFFF" "#FF6D6DFF" "#FF0000FF"
[2,] "#FF9292FF" "#FFFFFFFF" "#FFB6B6FF"
[3,] "#FF2424FF" "#FF4949FF" "#FFFFFFFF"

Where the additional FFs at the end are for the opacity which can be set with the alpha parameter.

You can strip those with:



     [,1]      [,2]      [,3]     
[1,] "#FFFFFF" "#FF6D6D" "#FF0000"
[2,] "#FF9292" "#FFFFFF" "#FFB6B6"
[3,] "#FF2424" "#FF4949" "#FFFFFF"

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download