我有一个饼图,它只会绘制一次。我从 Mike Bostock's pie chart example 得到的。我是 D3 的新手,我不明白为什么它不会重画。我看到this关于重新绘制条形图的帖子,但由于某种原因,该技术不适用于我的饼图。我确信我做错了什么。
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.percent; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
function drawChart(error, data) {
console.log("here");
data.forEach(function(d) {
d.percent = +d.percent;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) {
console.log("inside path");
return d.data.color;
});
g.append("text")
.attr("transform", function(d) { console.log("inside transform", d);return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.color; });
}
drawChart(undefined, [{"color": "green", "percent": 50}, {"color": "red", "percent": 50}]);
setTimeout(function () {
drawChart(undefined, [{"color": "green", "percent": 75}, {"color": "red", "percent": 25}]);
}, 1000)
最佳答案
问题 1:
您将 d 属性添加到 DOM g 中,这是错误的。
<g class="arc" d="M-240,2.939152317953648e-14A240,240 0 0,1 -4.408728476930471e-14,-240L0,0Z">
<path d="M-9.188564877424678e-14,240A240,240 0 1,1 1.6907553595872533e-13,-240L0,0Z" style="fill: red;">
</path>
<text transform="translate(-120,-9.188564877424678e-14)" dy=".35em" style="text-anchor: middle;">red</text>
</g>
d 属性仅适用于路径,不适用于 g。
所以这一行是不正确的
g.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
问题2:
您的更新函数不正确(同原因问题1)
function update (data) {
console.log("here", data);
var value = this.value;
g = g.data(pie(data)); // compute the new angles
g.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
};
在我看来,您应该再次调用 drawChart
函数进行更新。
但您可以像这样删除旧的 g 组。
svg.selectAll(".arc").remove();
优点是我们使用相同的代码来创建和更新 (DRY)。 所以你的超时函数就变成了这样
setTimeout(function () {
drawChart(undefined, [{"color": "green", "percent": 75}, {"color": "red", "percent": 25}]);
}, 2000);
完整工作代码here
希望这有帮助!
关于javascript - d3 饼图不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33925077/