2
我想通過將「年齡」和總體人口進行分組來創建一個餅圖。我怎麼能這樣做?Javascript summming arrays using using d3.nest()
Data.csv
age,population
<5,2704659
5-13,4499890
5-13,4
14-17,2159981
18-24,3853788
18-24,385
25-44,14106543
45-64,8819342
45-64,8142000
5-13,4499000
=65,612463
......應該是這樣:
age,population
<5,2704659
5-13,8998894
14-17,2159981
18-24,3854173
25-44,14106543
45-64,16961342
=65,612463
的index.html
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height)/2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
d3.csv("data.csv", function(error, data) {
var data = d3.nest()
.key(function (d) { return d.age; })
.sortKeys(d3.ascending)
.rollup(function (d) {
return d3.sum(d, function (g) { return g.population; });
}).entries(data);
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
</script>
你能看到的方式ŧ o修改此功能,以便返回所需的結果?
你目前得到什麼結果? –