Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top