D3: 2nd group of rect's interferes with 1st


I’m working on the D3 heatmap project.

My final task is to add a legend, which is made up of rectangles that connect to an array of colors. My heat map is also made up of rectangles, but those connect to the provided .json file.

I’ve found that when I add my legend of six rectangles, the first six rectangles of my heat map disappear. I don’t understand the D3 update pattern enough to understand why this is happening and how to get around it. If I make my legend out of circles instead of rectangles, I don’t have this problem.

Here is my project: https://codepen.io/tpmc123/pen/XPPopo?editors=1011
The legend code starts at line 55. And the heat map rectangles are drawn at line 130.

Here are those code snippets:

// --- create legend ---
var legend = g.append("g")
    .attr("id", "legend")
    .attr("transform", "translate(0," + (height + 40) + ")")

var legendRects = legend.selectAll("rect")
            .attr("width", 40)
            .attr("height", 20)
            .attr("x", (d,i) => i * 40)
            .attr("y", 0)
            .attr("fill", d => d)
// add rectangles
    var rects = g.selectAll("rect")
            .attr("class", "cell")
            .attr("data-month", d => d.month)
            .attr("data-year", d => d.year)
            .attr("data-temp", d => d.temperature)
            .attr("x", d => xScale(d.year)) // shifts bars 
            .attr("y", d => yScale(d.month)) // shifts bars
            .attr("width", xScale.bandwidth)
            .attr("height", yScale.bandwidth)
            .attr("fill", function(d) { return colorScale(d.temperatureRange); })

Can anyone explain why this is happening? And how to get around it?



Solution found at https://stackoverflow.com/questions/46489132/d3-rect-in-one-group-interfering-with-rect-in-another-group

When creating heat map rectangles, use var rects = g.selectAll("null") so that you don’t select pre-existing legend rectangles.