I have taken Mike Bostock's Sortable Bar Chart code (https://bl.ocks.org/mbostock/3885705) and converted it to a horizontal bar chart.
I'm having trouble with bars "vanishing" in the sort. The initial display is fine. All bars are displayed in descending order of the variable datesort and the y-axis displays the datesort variable. Then the first sort takes place and things start to fall apart. It sorts on ascending datesort and displays the value variable. But if more than one datesort has a value (ex: the datapoints with a datesort of 3,16,18,34,36 and 51 all have a value of 64) only the last bar (in this case the 51st bar) with the value of 64 is graphed.
Then if I uncheck the Sort Values checkbox, it sorts on descending value displaying the value variable. But there is only one bar for each value. So while I would expect to see six bars of length (value) 64 (corresponding to the datesorts of 3,16,18 etc.), it only graphs one.
I'm at a loss as to how to fix this so that all bars stay graphed and would appreciate assistance.
The pertinent portion of code:
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("height", y.bandwidth())
.attr("y", function(d) { return y(d.datesort); })
.attr("width", function(d) { return x(d.value); });
d3.select("input").on("change", change);
var sortTimeout = setTimeout(function() {
d3.select("input").property("checked", true).each(change);
}, 2000);
function change() {
clearTimeout(sortTimeout);
// Copy-on-write since tweens are evaluated after a delay.
var y0 = y.domain(data.sort(this.checked
? function(a, b) { return b.datesort - a.datesort; }
: function(a, b) { return d3.ascending(a.value, b.value); })
.map(function(d) { return d.value; }))
.copy();
svg.selectAll(".bar")
.sort(function(a, b) { return y0(a.value) - y0(b.value); });
var transition = svg.transition().duration(750),
delay = function(d, i) { return i * 50; };
transition.selectAll(".bar")
.delay(delay)
.attr("y", function(d) { return y0(d.value); });
transition.select(".y.axis")
.call(yAxis)
.selectAll("g")
.delay(delay);
Thanks.