Order nodes in d3 sankey diagram

I am trying to order nodes in a D3 sankey. I want the nodes to have higher values.

This is the appropriate code ( based on d3 noob code ) where I try to achieve what I want using the built-in D3 sort function. The result is not what I expect.

When checking sankey.js, I don’t quite understand how the plugin orders nodes. Any recommendations on this topic would be appreciated.

//set up graph in same style as original example but empty graph = {"nodes" : [], "links" : []}; data.forEach(function (d) { graph.nodes.push({ "name": d.source }); graph.nodes.push({ "name": d.target }); graph.links.push({ "source": d.source, "target": d.target, "value": +d.value }); }); //try to sort the nodes and links before indexing them (not working) graph.nodes.sort(function (a,b) {return d3.descending(a.value, b.value); }); graph.links.sort(function (a,b) {return d3.descending(a.value, b.value); }); // return only the distinct / unique nodes graph.nodes = d3.keys(d3.nest() .key(function (d) { return d.name; }) .map(graph.nodes)); // loop through each link replacing the text with its index from node graph.links.forEach(function (d, i) { graph.links[i].source = graph.nodes.indexOf(graph.links[i].source); graph.links[i].target = graph.nodes.indexOf(graph.links[i].target); }); //now loop through each nodes to make nodes an array of objects // rather than an array of strings graph.nodes.forEach(function (d, i) { graph.nodes[i] = { "name": d }; }); 
+5
source share
2 answers

Removing the following line from the resolveCollisions () function in the sankey.js file will stop the order in which the nodes change:

 function resolveCollisions() { ... // nodes.sort(ascendingDepth); // commented this out to prevent node reordering ... } 

Then the nodes will be ordered vertically, but they are initially populated. Therefore, if you first sort the nodes before clicking on the data, they will be displayed in sorted order.

+4
source

If you set the iterations layout value to zero, you will get the nodes in alphabetical order (by name): this worked enough for me.

 var sankey = d3.sankey() .nodeWidth(36) .nodePadding(40) .size([width, height]) .layout(0); /* <<<<<<< setting the iterations to zero */ 
+1
source

Source: https://habr.com/ru/post/1234950/


All Articles