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")

Now comes the exit selection:


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

    .attr("x", function(d, i) {
        return (d.hour) * gridSize;
    .attr("y", function(d) {
        return ( - 1) * gridSize;
    .attr("rx", 4)
    .attr("ry", 4)
    .attr("class", "hour bordered")
    .attr("width", gridSize)
    .attr("height", gridSize)
    .style("fill", colors[0])
    .style("fill", function(d) {
        return colorScale_sum(d.value);

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

    .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:

Related Query

More Query from same tag