我正在尝试根据此处的博客条目实施饼图:http://bl.ocks.org/mbostock/3887235
我想通过更新弧来增强描述的饼图。我的代码如下所示:
<!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; }
.arc path { stroke: #fff; } </style> <body> <script src="http://d3js.org/d3.v3.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 + ")");
var draw = function(data) { var g = svg.selectAll(".arc").data(pie(data));
g.each(function(d, i) {
var tmp = d3.select(this);
console.log(tmp);
tmp.select("path").attr("d", arc).attr("fill", function(d) {
return color(d.data.age);
});
tmp.select("text").attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
}).attr("dy", ".35em").style("text-anchor", "middle").text(function(d) {
return d.data.age;
}); });
g.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; });
g.exit().remove(); }
var startTimer = function startTimer() { setTimeout(function() {
var data = [];
data.push({
population : (Math.random() * 100),
age : "A"
});
data.push({
population : (Math.random() * 100),
age : "B"
});
data.push({
population : (Math.random() * 100),
age : "C"
});
data.forEach(function(d) {
d.population = +d.population;
});
console.log(data);
draw(data);
startTimer(); }, 2000); };
startTimer(); </script>
不幸的是,看起来弧线没有像预期的那样被移除。随着时间的推移,我得到超过三个弧(正如我所料)。谁能指出我做错了什么?
谢谢!