How Can I Bind An Array Of Objects To Arcs In A D3 Pie Chart?
I'm building a pie chart and my data is in the form of a JSON: [ { 'Stage':'birth', 'Avg':19071 }, { // } ] I don't know how I should use the data function to b
Solution 1:
You need to give your layout.pie
a value accessor function.
var pie = d3.layout
.pie()
.sort(null)
.value(function(d){
return d.Avg; //<-- d3 will pie the values in Avg property
});
Full working sample:
<!DOCTYPE html><html><head><scriptdata-require="d3@3.5.3"data-semver="3.5.3"src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script><linkhref="style.css" /><scriptsrc="script.js"></script></head><body><script>var data = [{
"Stage": "birth",
"Avg": 19071
}, {
"Stage": "death",
"Avg": 10000
}];
var svg = d3.select('body')
.append('svg')
.attr('width', 500)
.attr('height', 500);
var colors = d3.scale.category10();
var pie = d3.layout
.pie()
.sort(null)
.value(function(d) {
return d.Avg;
})
var arc = d3.svg.arc()
.outerRadius(90)
.innerRadius(0);
var arcs = svg.selectAll("g.arc")
.data(pie(data)) //<-- this is fine
.enter()
.append("g")
.attr({
"transform": "translate(" + 100 + "," + 100 + ")",
"class": function(d, i) {
return d.data.Stage; //<-- after pieing the data, the raw data is then in the data property
}
});
//Draw arc paths
arcs.append("path")
.attr({
"d": arc,
"class": "arc"
})
.style('fill', function(d,i){
returncolors(i);
})
</script></body></html>
Post a Comment for "How Can I Bind An Array Of Objects To Arcs In A D3 Pie Chart?"