D3 without explicit storage of rows and columns

I have a 2d dataset that I would like to visualize as a heatmap in D3.

From the above examples, including:

stack overflow

http://bl.ocks.org/2605010

it looks like you should encode the row and column as attributes of each data item. Is there a way to take advantage of the data structure (that is, the fact that it is a 2D array indexed with [i] [j] notation) to avoid redundant encoding of location information?

If not, is there a concise and / or efficient way to create a data structure that encodes location information? By this I mean something other than a nested loop:

myData = [[1, 2], [3, 4]] myDataWithPos = [] nRow = myData.length nCol = myData[0].length for (i = 0; i < nRow; i++){ for(j = 0; j < nCol; j++){ myDataWithPos.push({val: myData[i][j], row: i, col: j}) } } 
+4
source share
1 answer

Of course, you can use the indices of the 2d array to draw a heat map. I put together a quick example at http://jsfiddle.net/uArga/4/ .

Assuming your data looks like this:

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

First, I set up some basic scales for calculating the x and y offsets depending 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 parameters without having to manually recalculate how large each cell is.

 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"); 

Then add each cell to the row using a subquery. There may be a cleaner way to do this, but I basically just fix the row number next to the data for each cell. Then I use scales to determine 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); }); 
+4
source

Source: https://habr.com/ru/post/1442150/


All Articles