d3.js: add elements according to data-attribute value -
i simplified example as possible. have data.csv file , want create elements below (result). there 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 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 selects lines. don't know how select , enter lines same name parent g element.
you want use nest
operator this:
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; });
Comments
Post a Comment