Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a selection in d3.js disturbs the data-join

Tags:

d3.js

When I reorder a selection of paths in d3 with selection.sort(), the data-join is disturbed and my paths get reassigned to the wrong data objects.

I only want to reorder the paths so that some end up on top of others (as in z-index). I do not want to reassign data objects from one path to another.

How can I reorder the paths without disturbing the data-join?

_friends.selectAll('path').sort(function(a, b){
  return d3.ascending(a.Q, b.Q);
});
like image 864
Mark Avatar asked Jul 15 '12 23:07

Mark


1 Answers

It sounds like you need to specify a key function. This allows you to bind data by an arbitrary key, rather than relying on the default, which is to use the datum's position in the array i.e. the order (which in your case may change).

If you don't already have a unique key for each datum, you can always just generate them at load time:

var id = 0;
for (var i = 0; i < data.length; i++) data[i].id = id++;

If you create any new data you can continue to increment id to get a new, unique ID.

Then, for data binding you can do:

.data(data, function(d) { return d.id; })
like image 71
Jason Davies Avatar answered Nov 16 '22 02:11

Jason Davies