Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple PHP function to convert a number to a heatmap HTML background color?

My question is related to Algorithm to convert any positive integer to an RGB value but really it's not the same question -- that guy has mostly a data normalization problem, I actually have more of an aesthetic color selection problem.

I have a bunch of numbers between -1.0 and +1.0. I need to create a heatmap overlaid with text.

What is the simplest way, using PHP, to convert each number into an HTML color (#rrggbb), in such way that the resulting color not only is intuitively related to temperature (i.e. bluest for coldest and reddest for the hottest, with some smooth transition in between) but also that it's suitable as a background color for black-color text?

like image 419
Alex R Avatar asked Nov 21 '10 00:11

Alex R


1 Answers

I would implement it as a simple linear gradient between the red and blue components, using the sprintf function to encode to a hex value:

function toHeatColor($full) {
    $positive = ($full + 1) / 2;
    return sprintf("#%02xcc%02x", $positive * 51 + 204, (1 - $positive) * 51 + 204);
}

You can see how the range of colors looks at http://jsfiddle.net/9QQkU/. The corresponding values are -1, -0.75, 0, 0.75, and 1.

like image 80
PleaseStand Avatar answered Nov 11 '22 16:11

PleaseStand