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.
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | < html > < body > < svg class = "output" width = "500" height = "500" > </ svg > < 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,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6,5,5,4,4,3,3,2,1,0,0, 0,1,1,2,3,3,4,4,5,5,5,4,4,4,3,2,1,1,0,0, 0,1,1,2,3,3,4,4,5,5,5,4,4,4,3,2,1,1,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,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 > |