简体   繁体   中英

Sorting a stacked bar chart d3js

In this plunker I have the same problem as I had in my previous question where my data.sort function is technically sorting the bars as they should but not in the desired way.

Just like last time, I'd like em to be sorting like this rather than the way they're sorting now.

I've tried putting the data.sort alongside the x.domain and axis--x in various ways without any success and I'm all out of ideas.

Any help is as always appreciated!

updated plunker

You need to use key functions .data(d=>d,d=>d.data.State); , so that d3 knows which data is new, old, or existing. It's recommended to always use key functions, unless you want the data to be keyed by array index.

You also need to apply the x transformation to the existing bars.

Even though your example doesn't have new data after the initial data, it's still good practice to merge the enter selection with the update selection, and then run the transition.

let bars = g.selectAll("g.layer").selectAll("rect")
      .data(d=>d,d=>d.data.State);

  bars = bars.enter().append("rect")
      .attr("width", x.bandwidth()).merge(bars)
    .transition().duration(Globalvar.durations)
      .attr("x", function(d) { return x(d.data.State); })
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); });

notice how the merge code is more concise than writing the transition twice for both the enter and update selections.

let bars = g.selectAll("g.layer").selectAll("rect")
      .data(function(d) { return d; });

bars.enter().append("rect")
      .attr("width", x.bandwidth())
    .transition().duration(Globalvar.durations)
      .attr("x", function(d) { return x(d.data.State); })
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); });

  bars.transition().duration(Globalvar.durations)
      .attr("y", function(d) { return y(d[1]); })
      .attr("height", function(d) { return y(d[0]) - y(d[1]); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM