5

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();
  }
}
xxx
  • 1,153
  • 1
  • 11
  • 23
sudocity
  • 377
  • 6
  • 14
  • 2
    To remove unused nodes you should just do a node.exit().remove() in your update function after you checked that all the conditions for keeping nodes on screen are met. It's really hard to say in this case where is the mistake, as you probably have the logic for adding/removing nodes split between several functions and you only display one of them.... I guess you should just assign a score or something to each node that is more likely to stay on the screen and then do a simple filter by score > x or something... it's just an idea, that's why I left it as a comment and not an answer. – paxRoman Oct 24 '12 at 09:41

1 Answers1

2

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

Christopher Chiche
  • 15,075
  • 9
  • 59
  • 98