score:2

Accepted answer

Do not remove elements only to re-append them in a D3 code, as suggested in the comments: this is not the idiomatic solution, it's a slow and ineffective workaround and it can make things way harder further in the code. This is what I call a lazy update.

Instead of that, use proper enter/update/exit selections. Here is a refactor of your code, in which I'm purposely avoiding merge(), which is difficult to understand at first, hence some code duplication.

Here it is, this is the update selection:

var cards = svg_sum.selectAll(".hour")
    .data(flatList);

Now comes the exit selection:

cards.exit().remove();

Then, you have the enter selection, with the transition:

cards.enter().append("rect")
    .attr("x", function(d, i) {
        return (d.hour) * gridSize;
    })
    .attr("y", function(d) {
        return (d.day - 1) * gridSize;
    })
    .attr("rx", 4)
    .attr("ry", 4)
    .attr("class", "hour bordered")
    .attr("width", gridSize)
    .attr("height", gridSize)
    .style("fill", colors[0])
    .transition().duration(1000)
    .style("fill", function(d) {
        return colorScale_sum(d.value);
    });

And, again, the same transition for the update selection.

cards.transition().duration(1000)
    .style("fill", function(d) {
        return colorScale_sum(d.value);
    });

As I said, you can avoid that repetition using merge(). Things are more complicated regarding the legend, since you have groups there (have a look at my fork to see the selections).

Here is your updated bl.ocks: http://bl.ocks.org/GerardoFurtado/d938a52519b4701704137e8c8e6c826d/bacf8134a81c37e977094fe80afd6c12866b7c58


Related Query

More Query from same tag