Reputation: 23
I'm trying to have my text labels move and change while sorting. I have a multidimensional array including bar height, width, and opacity. A kind contributor helped me out yesterday with getting the bars sorted correctly, but I'd also like to get the text labels to move and change at the top of each bar as the bar sorts and moves.
var s = -1;
svg.on("click", function() {
s = (s + 1) % 3;
var xPosition = parseFloat(d3.select(this).attr("x")) xScale.bandwidth() / 2;
var yPosition = parseFloat(d3.select(this).attr("y")) + 14;
svg.selectAll("rect")
.sort(function(a, b) {
return d3.ascending(a[s], b[s]);
})
.transition()
.delay(function(d, i) {
return i * 65;
})
.duration(250)
.attr("x", function(d, i) {
return xScale(i);
});
svg.selectAll("text")
.append("text")
.text(function(d) {
return d[s];
})
.attr("text-anchor", "left")
.attr("x", xPosition)
.attr("y", yPosition)
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "red");
});
As you can see, I'm quite lost as to where to go moving forward. I took the xPosition and yPosition variable idea from a textbook but it doesn't seem to change anything. Also, the text labels never change while I sort through height, width, and opacity. Thanks for the help.
Upvotes: 1
Views: 31
Reputation: 102174
When you do this...
svg.selectAll("text")
.append("text")
//etc...
... you are appending <text>
elements inside <text>
elements, which makes no sense.
Instead of that, assuming that your texts were previously created, just select them and sort them accordingly:
svg.selectAll("text")
.text(function(d) {
return d[s];
})
.attr("x", xPosition)
.attr("y", yPosition);
Upvotes: 1