rubik
rubik

Reputation: 9104

Selecting nested data in D3

I have an object similar to this one:

[{name: 'x', values: [1, 2, 3]}, {name: 'y', values: [4, 5, 6]}]

I'd like to traverse it with D3.js and generate the following SVG:

<svg width="100" viewBox="0 0 50 50">
  <g transform="translate(0,10)">
    <circle cx="5" r="1"></circle>
    <circle cx="15" r="2"></circle>
    <circle cx="25" r="3"></circle>
  </g>
  <g transform="translate(0,30)">
    <circle cx="5" r="4"></circle>
    <circle cx="15" r="5"></circle>
    <circle cx="25" r="6"></circle>
  </g>
</svg>

This is my attempt:

data = [{name: 'x', values: [1, 2, 3]}, {name: 'y', values: [4, 5, 6]}];
var chart = d3.select('#chart').attr('width', 100);
var row = chart.selectAll('g')
  .data(data)
  .enter().append('g')
  .attr('transform', function(d, i) { return 'translate(0,' + 10 + i*20 + ')';})
  .append('circle').attr('r', function(d) {console.log(d);});

I didn't finish it because it does not work already. From the console I see that in the second append, d is every element of the original array. How do I descend into the structure? I'd like to iterate through the values of the values array in the second append.

Upvotes: 3

Views: 72

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

For making groups you are doing it correctly except for the part where you appending circle:

var gs = svg.selectAll(".group")
  .data(data)//make as many group as data
  .enter()
  .append("g")
  .attr('transform', function(d, i) {
    return 'translate(0,' + (10 + i * 20) + ')';
  })
  .attr("class", "group");

For making circles you should be doing the following, on each group take its value and make circles.

var circles = gs.selectAll(".mycircle")
  .data(function(d) {
    return d.values; //circle made in terms of values array of each group
  })
  .enter()
  .append("circle")
  .attr("class", "mycircle")
  .attr("r", 4)
  .attr("cx", function(d, i) {
    if (i == 0)
      return 5;
    if (i == 1)
      return 15;
    if (i == 2)
      return 25;
  })

Your question: How do I descend into the structure?

Below is the code, how you have to descend into the structure,

.data(function(d) {
        return d.values; //circle made in terms of values array of each group
      })

Working code here

Upvotes: 1

Related Questions