Accepted answer

Here you go! There was not much change required in your previous code.


So this was related to the data binding to the barGroups. Every time the data was sorted or changed, new data was bound to the "g.layer" and with d3's update methodology, this would how it would work.

Changes in the new code:

  • Moved barGroups code above the data sorting with no transform attribute.
  • Added transform attribute to the groups after x0 domain is defined.

Relevant code:

Above the sort function:

// bars
let barGroups = g.selectAll("g.layer").data(data);
  .classed('layer', true);


Once x0 domain is set:

  .attr("transform", function(d, i) {
    return "translate(" + x0(d.State) + ",0)";

Hope this helps! :)

Related Query