2

I simplified example as much as possible. I have data.csv file and want to create elements as below (Result). Is there some elegant way? Thank you.

Data (data.csv):

id, name, value
1, fruits, apple
2, fruits, pear
3, fruits, strawberry
4, vegetables, carrot
5, vegetables, celery
...

Result:



    <g class="groups" id="fruits">
      <circle class="some" id="apple"/>
      <circle class="some" id="pear"/>
      <circle class="some" id="strawberry"/>
      ...
    </g>
    <g class="groups" id="vegetables">
      <circle class="some" id="carrot">
      <circle class="some" id="celery">
      ...
    </g>

I tried something like this:



    d3.csv("data.csv", function(data) {
    var svg = ...
    var groups = svg.selectAll(".groups")
                  .data(data)
                  .enter().append("g")
                  .attr("class", "groups")
                  .attr("id", function(d) { return d.name; });

        groups.selectAll(".some")
        .data(data, function(d) { return d.id; })
        .enter().append("circle")
        .attr("class", "some")
        .attr("id", function(d) { return d.value; });
   });

But it selects all lines. I don't know how to select and enter only lines with the same name as parent g element.

4

1 回答 1

1

您想为此使用nest运算符

var byName = d3.nest().key(function(d) { return d.name; })
                      .entries(data);
var groups = svg.selectAll(".groups").data(byName)
                .enter().append("g")
                .attr("class", "groups")
                .attr("id", function(d) { return d.key; });
var circles = groups.selectAll(".some")
                    .data(function(d) { return d.values; })
                    .enter().append("circle")
                    .attr("class", "some")
                    .attr("id", function(d) { return d.value; });
于 2013-07-22T12:47:19.723 回答