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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With