d3.js v4: How to access parent group's datum index?

前端 未结 8 718
萌比男神i
萌比男神i 2020-11-28 10:33

The description of the selection.data function includes an example with multiple groups (link) where a two-dimensional array is turned into an HTML table.

8条回答
  •  情话喂你
    2020-11-28 11:23

    Here's a snippet I crafter after re-remembering this usage of .each for nesting, I thought it may be useful to others who end up here. This examples creates two layers of circles, and the parent group index is used to determine the color of the circles - white for the circles in the first layer, and black for the circles in the top layer (only two layers in this case).

    const nested = nest().key(layerValue).entries(data);
    
    let layerGroups = g.selectAll('g.layer').data(nested);
    layerGroups = layerGroups.enter().append('g').attr('class', 'layer')
      .merge(layerGroups);
    
    layerGroups.each(function(layerEntry, j) {   
      const circles = select(this)
        .selectAll('circle').data(layerEntry.values);
      circles.enter().append('circle')
        .merge(circles)
          .attr('cx', d => xScale(xValue(d)))
          .attr('cy', d => yScale(yValue(d)))
          .attr('r', d => radiusScale(radiusValue(d)))
          .attr('fill', j === 0 ? 'white' : 'black'); // <---- Access parent index.
    });
    

提交回复
热议问题