skalb.com

Multi-color Heat Map in JavaScript

While working on my flight grid site, I was looking for a way to add a multi-color heat map.

I found the following example, but for just one color.

I modified it to work for two colors as shown below (warning messy code!):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<script type="text/JavaScript">
$(document).ready(function(){
  // Function to get the Max value in Array
    Array.max = function( array ){
        return Math.max.apply( Math, array );
    };

    // get all values
    var counts= $('#heat-map-3 tbody td').not('.stats-title').map(function() {
        return parseInt($(this).text());
    }).get();

  // return max value
  var max = Array.max(counts),
      middle = max * 1.0 / 2;

  // add classes to cells based on nearest 10 value
  $('#heat-map-3 tbody td').not('.stats-title').each(function(){
      var val = parseInt($(this).text());
    if (val < middle) {
      var pos = parseInt(Math.round((val/middle)*100)).toFixed(0);
          relative = parseInt(pos / 100.0 * 225).toFixed(0);
          clr = 'rgb('+relative+','+255+','+relative+')';
          $(this).css({backgroundColor:clr});
    }
    else {
      var pos = parseInt(100 - Math.round(((val-middle)/(max-middle))*100)).toFixed(0);
      relative = parseInt(pos / 100.0 * 225).toFixed(0);
      clr = 'rgb('+255+','+relative+','+relative+')';
      $(this).css({backgroundColor:clr});
    }
  });
});
</script>

Here’s a working example.

Comments