0

How do I update a vertical bar chart in d3 after having sorted the array of objects holding my data?

My (surely petty) problem is best seen here : http://jsfiddle.net/yJq3e/3/

After the bars creation, I call the sortBars() function, which works fine (as console.log can tell me) until I update the y-attribute. I assume it's connected to the y-attribute being actually dependent on the index (or the key?). However, I would've thought calling

.attr("y", function(d) { return y(d.name); })

on the .bar-attribute again after sorting should suffice as it does when I set the attribute for the initial position of the bars.

any help much appreciated !

1 Answer 1

2

What you would do in D3 is to sort the underlying data and pass that to .data() again. Like so:

svg.selectAll(".bar")
   .data(dataset.sort(function(a, b) { return b.value - a.value; }))

The rest of the code can remain unchanged. I've added a transition to make it look nicer. Complete example here.

Sign up to request clarification or add additional context in comments.

6 Comments

This makes a lot of sense ! It doesn't seem to order it descendingly though. Using d3.descending doesn't change this. Again, console.log shows the correct order but the bars end up in a different, yet still unordered way. Any ideas top of mind?
The problem is that the y position is determined by the name, which doesn't change. You could determined it based on the index of the data point -- jsfiddle.net/yJq3e/10
I'd vote your answer up if I had any reputation. Will be back when I've grown up ... much obliged !
I'm not sure this is ok to bug you again, but - after a break - I'm back in the sorting-struggle...
My first question would be : can you explain the use of the line function (d) {return d.name;} after the comparator function ? In what capacity is d.name used? Secondly, I added an ascending, descending and undo sort functionality like so : jsfiddle.net/yJq3e/16 (surely there are more elegant ways with less code). All work fine, but after I hit the undo sort button d3 doesn't order the values but the array-index, although all sort functions clearly work on d.value. Can you help me understand? Apologies for the pester - my little brain is breaking ..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.