d3 v4: merge enter and update selections to remove duplicate code

我的梦境 提交于 2019-12-01 09:55:27

问题


I understand that merge can be used to combine enter and update selections in d3 v4, as in the simple example here: https://bl.ocks.org/mbostock/3808218.

I have a scatter plot in which multiple variables are displayed on a shared x-axis, for different groups selected by a dropdown box. When a new group is selected, the overall set of datapoints is updated, with points for each variable added like this:

.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();

This whole piece of code is largely duplicated for the overall enter selection and again in the overall update selection (as opposed to the individual variables), which seems less than ideal. How would merge be used to to remove this duplicated code?

The full example is here: http://plnkr.co/edit/VE0CtevC3XSCpeLtJmxq?p=preview


回答1:


I'm the author of the solution for your past question, which you linked in this one. I provided that solution in a comment, not as a proper answer, because I was in a hurry and I wrote a lazy solution, full of duplication — as you say here. As I commented in the same question, the solution for reducing the duplication is using merge.

Right now, in your code, there is duplication regarding the setup of the "update" and "enter" selections:

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
});

To avoid the duplication, we merge the selections. This is how you can do it:

var enter = update.enter().append("g")
    .attr("class", "datapoints")
    .merge(update)
    .each(function(d, i) {
        //etc...

Here is the updated Plunker: http://plnkr.co/edit/MADPLmfiqpLSj9aGK8SC?p=preview



来源:https://stackoverflow.com/questions/48178618/d3-v4-merge-enter-and-update-selections-to-remove-duplicate-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!