Simple basic heatmap in D3.JS
The code below creates the extremely basic heatmap shown above using D3.JS. The heatmap data is stored in a flat 1D array, so X and Y dimensions need to be provided. I don’t think it would be too hard to modify this to process 2D arrays.
<html>
<body>
<svg class="output" width="500" height="500">
</svg>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var max_value = 9;
// This function converts a 0->max_value number to a rgb string for the heatmap
function get_rgb(d) {
var ratio = 2 * (d/max_value)
var r = Math.floor(Math.max(0, 255*(ratio - 1)))
var b = Math.floor(Math.max(0, 255*(1 - ratio)))
var g = 255 - b - r
return "rgb(" + r + "," + g + "," + b + ")";
}
var svg = d3.select(".output")
var mydata = [
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,
0,0,0,0,1,1,1,2,2,2,2,2,1,1,1,0,0,0,0,0, 0,0,0,0,1,1,1,2,2,2,2,2,1,1,1,0,0,0,0,0,
0,0,0,1,1,2,2,3,3,3,3,3,2,2,1,1,0,0,0,0, 0,0,0,1,1,2,2,3,3,3,3,3,2,2,1,1,0,0,0,0,
0,0,1,1,2,3,3,3,4,4,4,3,3,3,2,1,1,0,0,0, 0,0,1,1,2,3,3,3,4,4,4,3,3,3,2,1,1,0,0,0,
0,0,1,1,2,3,4,4,4,5,4,4,4,3,2,2,1,0,0,0, 0,0,1,1,2,3,4,4,4,5,4,4,4,3,2,2,1,0,0,0,
0,1,1,2,3,3,4,5,5,6,5,5,4,4,3,3,2,1,0,0, 0,1,1,2,3,3,4,5,5,6,5,5,4,4,3,3,2,1,0,0,
0,1,2,2,3,4,4,5,6,7,6,5,5,4,4,3,2,1,0,0, 0,1,2,2,3,4,4,5,6,7,6,5,5,4,4,3,2,1,0,0,
0,1,2,3,3,4,5,5,6,8,7,6,5,5,4,3,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2,1,0,0,0, 0,0,1,1,2,3,3,4,4,4,4,4,3,3,3,2,1,0,0,0,
0,0,1,1,2,2,3,3,3,4,4,3,3,2,2,1,1,0,0,0, 0,0,1,1,2,2,3,3,3,4,4,3,3,2,2,1,1,0,0,0,
0,0,0,1,1,2,2,2,3,3,3,2,2,2,1,1,0,0,0,0, 0,0,0,1,1,2,2,2,3,3,3,2,2,2,1,1,0,0,0,0,
0,0,0,0,1,1,1,2,2,2,2,2,1,1,1,0,0,0,0,0, 0,0,0,0,1,1,1,2,2,2,2,2,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
]
var selection = svg.selectAll("rect")
.data(mydata)
var cellsize = 5;
var x_dim = 40;
var y_dim = 40;
selection.enter().append("rect")
.attr("x", function(d,i) { return (i%x_dim)*cellsize; })
.attr("y", function(d,i) { return (Math.floor(i/x_dim))*cellsize; })
.attr("width", cellsize)
.attr("height", cellsize)
.style("fill", function(d) {return get_rgb(d);})
</script>
</body>
</html>
