Robert Andersson
Robert Andersson

Reputation: 1521

How to sort a grouped bar-chart d3js v4

In this block (FIXED) I've tried to do a sorting function in a similar fashion to this.

It technically sorts the bars but not in the expected way, if you check the sorting checkbox and shift years you can see what I mean.

I thought that it had something to do with the fact that it's only sorting based on data and not keys and/or the copy variable but I've tried sorting in all kinds of ways based on the mentioned variables without any success.

Not sure what I'm missing, appreciate any help!

Upvotes: 0

Views: 404

Answers (1)

Shashank
Shashank

Reputation: 5670

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

Plunker

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);
barGroups.enter().append("g")
  .classed('layer', true);

barGroups.exit().remove();

Once x0 domain is set:

g.selectAll("g.layer").transition().duration(Globalvar.durations)
  .attr("transform", function(d, i) {
    return "translate(" + x0(d.State) + ",0)";
  });

Hope this helps! :)

Upvotes: 1

Related Questions