Reputation: 1521
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!
Upvotes: 0
Views: 313
Reputation: 15992
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]); });
Upvotes: 1