Search code examples
graphcolorschartsvisualizationheatmap

What is the algorithm to create colors for a heatmap?


Assuming values are normalized from 0 to 1, what is the algoritm to get a color to create a heatmap like this?

1 is red, .5 is green, 0 is dark blue.

Working in RMagick / ImageMagick.

heatmap


Solution

  • 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.