Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check d3 js force graph for nodes with no links and remove them?

I would like to keep my nodes under control so that each of them is linked and there are no lonely nodes.

My script adds a pair of new nodes every 30 seconds from a JSON query. If either of the new nodes is a duplicate of an existing node, the graph will only be updated with the unique node and link it to the other existing node.

While this is going on, I'm shifting off the oldest nodes to keep a maximum of 10 nodes on the graph. It is here that I seem to be running into trouble. How can I go about removing nodes and check for and remove any stragglers, nodes that are not linked to any others?

The script is based on knoren's post on adding new nodes.

this.checkLength = function () {
  if (nodes.length > 10) {
    var i = links.shift();
    nodes.splice(findNodeIndex(i),1);
    update();
  }
}
like image 633
sudocity Avatar asked Nov 04 '22 14:11

sudocity


1 Answers

As suggested by paxRoman, in order to remove a node you can do:

node.exit().remove();

Now, to find empty nodes, what you can do is use the weight property of force nodes as explained in the documentation of the force layout:

weight - the node weight; the number of associated links.

So, finally, in order to get all nodes that are empty you can do:

force.nodes().filter(function(d){d.weight==0})

with force being your force layout.

Please also notice that the weight property will only be initialized on force.start() call as explained in the documentation:

These attributes do not need to be set before passing the nodes to the layout; if they are not set, suitable defaults will be initialized by the layout when start is called

like image 74
Christopher Chiche Avatar answered Nov 08 '22 14:11

Christopher Chiche