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');

For the update selection:


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


Complete demo here.

Related Query