score:2

Accepted answer

The source of the issues you're seeing is that you have your text and rect elements grouped in g elements. You need to handle enter, update and exit selections only for the g elements. Everything else hangs off of that. This implies that you need to save the enter selection for the g elements and then append the other elements to that.

The structure would look like this:

 var barEnter = bar.enter().append('g');
 barEnter.append("rect");
 barEnter.append("text");

For the update selection:

 bar.transition()...
 bar.select("rect").transition()...
 bar.select("text").transition()...

For the exit selection, you just need to remove the g elements because that will also remove everything contained within them:

 bar.exit().remove();

Complete demo here.


Related Query