gpt4 book ai didi

javascript - D3.js : Removing dynamically added Pie Chart slices

转载 作者:行者123 更新时间:2023-11-28 01:30:30 26 4
gpt4 key购买 nike

我能够生成饼图并根据用户交互动态向其中添加数据。

这是 fiddle http://jsfiddle.net/L5Q8r/

我面临的问题是从饼图中删除数据期间。当取消选中该复选框时,我将从“数据集”中删除数据并更新图表。

图表正在更新,但用户仍然可以看到之前的“饼图”。

我尝试添加“.exit().remove()”但没有成功。这是我所做的:

var updateChart = function (dataset) {
arcs.data(pie(dataset))
.enter()
.append("path")
.attr("stroke", "white")
.attr("stroke-width", 0.8)
.attr("fill", function (d, i) {
return color(i);
})
.attr("d", arc);

arcs.data(pie(dataset)).exit().remove(); // Executing but not working

arcs.transition()
.duration(duration)
.attrTween("d", arcTween);

sliceLabel.data(pie(dataset));

sliceLabel.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + (arc.centroid(d)) + ")";
})
.style("fill-opacity", function (d) {
if (d.value === 0) {
return 1e-6;
} else {
return 1;
}
});

sliceLabel.data(pie(dataset))
.enter()
.append("text")
.attr("class", "arcLabel")
.attr("transform", function (d) {
return "translate(" + (arc.centroid(d)) + ")";
})
.attr("text-anchor", "middle")
.style("fill-opacity", function (d) {
if (d.value === 0) {
return 1e-6;
} else {
return 1;
}
})
.text(function (d) {
return d.data.Population;
});
sliceLabel.data(pie(dataset)).exit().remove();//executing but not working
};

如有任何帮助,我们将不胜感激。 TIA。

最佳答案

这里有两件事。首先,您绑定(bind)数据两次:

arcs.data(pie(dataset))
// ...
arcs.data(pie(dataset)).exit()...

第二次将拾取您之前刚刚添加的弧线,这不是您想要的。执行一次数据绑定(bind)并将结果保存在变量中:

var sel = arcs.data(pie(dataset));
sel.enter()...
sel.exit()...

这让我想到第二件事。您没有在任何地方保存更新的选择,从而导致以后出现问题。在选择上调用 .data() 会修改基础数据,但不会更新选择。也就是说,无论您对 .enter() 执行什么操作,arcs 在调用 .data() 之前和之后都引用相同的元素等等

我已经解决了这两个问题 here 。对于后者,我显式地重新选择数据应绑定(bind)到的元素(例如 arc_grp.selectAll("path"))。还有其他方法可以做到这一点,但是这个方法明确了您正在使用的内容。

关于javascript - D3.js : Removing dynamically added Pie Chart slices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22173124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com