score:1

Accepted answer

The background rect is being 'consumed' by the d3 selection because you map your data to all of the rects in the element with svg.selectAll('rect').data(data). When you then use the .enter() method, it selects all of the bits of data you have that don't already have a matching DOM element. Since one of your data has a matching DOM element, that one is not in the selection provided by .enter().

To fix this, all you need to do is change the selection from rect to something that describes only your data, such as a class. Try this instead:

svg.selectAll(".rectClass")
  .data(dataset)
  .enter()
  .append("rect")
  .classed('rectClass', true)
  .attr("height",5)
  .attr("width",5)
  .attr("x",function(d){return d;})

Related Query