Question

I have a force directed graph, with 3 colors (red, green, and orange) for links. is it possible to sort links according to there colors?

Thanks and best regards.

Was it helpful?

Solution

d3 has a sort method that operates on selections. So if you're wanting to sort the selection by color, you might do it this way:

var order = {red: -1, green: 0, orange: 1};

var links = d3.selectAll('line.link')
  // a and b are data items, in this case links. This code assumes that there
  // exists a color property on the links which is 'red', 'green', or 'orange'.
  .sort(function(a, b) {
    return order[a.color] < order[b.color] ? -1 : order[b.color] < order[a.color] ? 1 : 0;
  });

It appears from the documentation that this also sorts DOM elements so that the document order is equivalent to the selection order:

selection.sort(comparator)

Sorts the elements in the current selection according to the specified comparator function. The comparator function is passed two data elements a and b to compare, returning either a negative, positive, or zero value. If negative, then a should be before b; if positive, then a should be after b; otherwise, a and b are considered equal and the order is arbitrary. Note that the sort is not guaranteed to be stable; however, it is guaranteed to have the same behavior as your browser's built-in sort method on arrays.

selection.order()

Re-inserts elements into the document such that the document order matches the selection order. This is equivalent to calling sort() if the data is already sorted, but much faster.

The order method makes DOM element order match the selection order, and is preferable if the selection is already sorted.

Documentation:

selection.sort()

selection.order()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top