问题
I'm creating a pie chart from a JSON file. I wonder if there is a way I can take some names from the JSON file and assign them as class names of the arcs created by d3.layout.pie().
Here is an example I created: http://blockbuilder.org/jinlong25/532d889e01d02cef2d24
Essentially, I want to do something like the last line of code below:
var data = [
{
'name': 'apple',
'value': 250
},
{
'name': 'banana',
'value': 100
},
{
'name': 'orange',
'value': 150
}
];
var arcs = svg.selectAll('g.arc')
.data(pie(data.map(function(d) { return d.value; })))
.enter().append('g')
.attr('transform', 'translate(70, 70)')
.attr('class', function(d) { return d.name; };
but since the data has been transformed by pie(), I wonder if there is anyway to add class names to the data generated by pie().
thanks!
回答1:
Some D3 layouts mutate the original dataset but others create a new dataset (like voronoi). In those cases, you can use the array position from the original dataset when working with the new dataset. So from your example:
var arcs = svg.selectAll('g.arc')
.data(pie(data.map(function(d) { return d.value; })))
.enter().append('g')
.attr('transform', 'translate(70, 70)')
.attr('class', function(d,i) { return data[i].name; };
回答2:
d3's layouts helpfully provide a .value() accessor which allows you to specify how get the value of the datum, instead of doing the data.map() operation. So, you could do:
var pie = d3.layout.pie().value(function(d) { return d.value; })
That way, your original datum is preserved in d.data.
So using that definition of pie, your code would change to this:
var arcs = svg.selectAll('g.arc')
.data(pie(data))
.enter().append('g')
.attr('transform', 'translate(70, 70)')
.attr('class', function(d) { return d.data.name; };
edit: added link the relevant documentation.
来源:https://stackoverflow.com/questions/34821449/adding-class-names-to-arcs-from-data-in-d3-layout-pie