我知道 merge
可用于合并 d3 v4 中的输入和更新选择,如这里的简单示例所示:https://bl.ocks.org/mbostock/3808218 .
我有一个散点图,其中多个变量显示在共享的 x 轴上,用于通过下拉框选择的不同组。选择新组时,将更新整个数据点集,并像这样添加每个变量的点:
.each(function(d, i) {
var min = d3.min(d.values, function(d) { return d.value; } );
var max = d3.max(d.values, function(d) { return d.value; } );
// Join new data with old elements
var points = d3.select(this).selectAll("circle")
.data(d.values, function(d) { return (d.Plot); } );
// Add new elements
points.enter().append("circle")
.attr("cy", y(d.key))
.attr("r", 10)
.style("opacity", 0.5)
.style("fill", function(d) { return elevColor(d.Elevation); })
.merge(points) //(?)
.transition()
.attr("cx", function(d) { return x((d.value-min)/(max-min)); });
// Remove old elements not present in new data
points.exit().remove();
这整段代码在整体输入选择和整体更新选择(与单个变量相反)中大部分都是重复的,这似乎不太理想。 merge
将如何用于删除此重复代码?
最佳答案
我是 solution for your past question 的作者,您在此链接中。我在评论中提供了那个解决方案,而不是一个正确的答案,因为我很匆忙,我写了一个懒惰的解决方案,充满了重复——正如你在这里所说的。作为I commented在同一个问题中,减少重复的解决方案是使用merge
。
现在,在您的代码中,关于“更新”和“输入”选择的设置存在重复:
var update = g.selectAll(".datapoints")
.data(filtered[0].values);
var enter = update.enter().append("g")
.attr("class", "datapoints");
update.each(function(d, i){
//code here
});
enter.each(function(d, i){
//same code here
});
为避免重复,我们合并
选择。这是你可以做到的:
var enter = update.enter().append("g")
.attr("class", "datapoints")
.merge(update)
.each(function(d, i) {
//etc...
这是更新的 Plunker:http://plnkr.co/edit/MADPLmfiqpLSj9aGK8SC?p=preview
关于javascript - d3 v4 : merge enter and update selections to remove duplicate code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48178618/