Using D3 with a multidimensional array / object

I have a JSON file with the following format:

{ "John":{ "name":"John", "counts":[ 1, 5, 10, 6 ] }, "Steve":{ "name":"Steve", "counts": [ 6, 4, 50, 40 ] } } 

I am trying to do a D3 visualization that makes a simple column table for these counts, with a title label on the left. When I have one series of data and a name, I can do it like this:

 svg.selectAll("rect").data([ 1, 5, 10, 6 ]).enter().append("rect") .attr("x",function(d,i) { return i*columnWidth; }) .attr("y",function(d) { return (rowHeight-scale(d));}) .attr("width",columnWidth) .attr("height",function(d) { return snowScale(d); } ); svg.selectAll("text").data("John").enter().append("text") .text(function(d) { return d; }) .attr("x",nameBuffer) .attr("y",function(d,i) { return rowHeight; }) .attr("font-size", "14px"); 

This works for a single row with data transmitted directly, with a text label on the left, and then a series of columns of the same width for each data point. But I am just starting with D3, and I cannot understand for life how to combine something together that goes through each object and creates a new line for each, each time adding to the vertical offset.

How can I execute a loop by creating for each object in the file and then creating text + columns for each row, preserving various nested values ​​and array indices?

+6
source share
1 answer

The key to achieving what you want is using nested choices. The idea is to pass the entire data object to the first level and create an SVG group for the elements. For each of these elements, the actual visualization is then added in the same way as you are doing now.

Check out Mike’s nested election tutorial . Remember to replace your hard-coded data calls with appropriate elements, for example. .data(d.counts) instead of .enter([1, 5, 10, 6]) .

+6
source

All Articles