What is the algorithm to create colors for a heatmap?

Here is a JavaScript code snippet to generate CSS hsl color code from [0, 1] value

function heatMapColorforValue(value){
  var h = (1.0 - value) * 240
  return "hsl(" + h + ", 100%, 50%)";
}

This algorithm is based on the 5 color heatmap,

In this algorithm, the colors corresponding with values are

0    : blue   (hsl(240, 100%, 50%))
0.25 : cyan   (hsl(180, 100%, 50%))
0.5  : green  (hsl(120, 100%, 50%))
0.75 : yellow (hsl(60, 100%, 50%))
1    : red    (hsl(0, 100%, 50%))

So simple!


I found this surprisingly easy to do with HSL.

In Ruby:

def heatmap_color_for value # [0,1]
  h = (1 - value) * 100
  s = 100
  l = value * 50
  "hsl(#{h.round(2)}%,#{s.round(2)}%,#{l.round(2)}%)"
end

This method returns HSL values as a string between 0% and 100%. It can be used with RMagick or ImageMagick.

Reference: ImageMagick HSL documentation.

In Java, for CSS, tested:

private String getHeatmapColorForCSS(double normalizedValue0to1) {
    double h = (1 - normalizedValue0to1) * 360;
    double s = 100;
    double l = 50;
    return String.format("hsl(%.2f, %.2f%%, %.2f%%)", h, s, l);
}

Note the key difference between CSS and ImageMagick: the first value is 0-360 and without a percent sign.