Using D3 with a multi-dimensional array/object

13,488

The key to achieving what you want is to use nested selections. The idea is to pass your whole data object to the first level and create an SVG group for the elements. For each of those elements, the actual visualization is then added in a similar fashion to what you're doing now.

Have a look at Mike's tutorial on nested selections. Remember to replace your currently hardcoded data calls with the respective elements, e.g. .data(d.counts) instead of .enter([1, 5, 10, 6]).

Share:
13,488
NChase
Author by

NChase

Web developer somewhere between total amateur and real professional.

Updated on July 26, 2022

Comments

  • NChase
    NChase almost 2 years

    I have a JSON file with a format like the following:

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

    I'm trying to do a D3 visualization that does a simple column chart for those counts, with a name label to the left. When I have a single data series and a name I can do it like so:

    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 the data supplied directly, with the text label off to the left and then a series of columns of equal width for each datapoint. But I'm just starting out with D3, and I can't for the life of me figure out how to chain something together that loops through each object and creates a new row for each, adding to the vertical offset each time.

    How can I loop through, creating a for each object in the file, and then creating the text + columns for each row, while preserving the different nested values and array indices?