score:5

Accepted answer

sure, you can use the indices of a 2d array to draw a heatmap. i put together a quick example at http://jsfiddle.net/uarga/4/.

assuming that your data looks like this:

var data = [[3,5],[9,2]];

first i set up some basic scales to calculate the x and y offsets based on the size of the data and the size of the chart. this makes it easy to resize the chart by changing the height and width without having to manually recalculate how big each of the cells should be.

var x = d3.scale.linear()
    .range([0, width])
    .domain([0,data[0].length]);

var y = d3.scale.linear()
    .range([0, height])
    .domain([0,data.length]);

you can then add each row to the heat map

var row = svg.selectall(".row")
             .data(data)
           .enter().append("svg:g")
             .attr("class", "row");

and then add each cell to the row using a subselect. there might be a cleaner way to do this but i basically just capture the row number alongside the data for each cell. i then use the scales to figure out the x, y, height, and width for each cell.

var col = row.selectall(".cell")
    .data(function (d,i) {return d.map(function(a){return {value: a, row: i};})})
  .enter().append("svg:rect")
    .attr("class", "cell")
    .attr("x", function(d, i) { return x(i); })
    .attr("y", function(d, i) { return y(d.row); })
    .attr("width", x(1))
    .attr("height", y(1))
    .style("fill", function(d) { return colorscale(d.value); });

Related Query