Schmoo
Schmoo

Reputation: 584

D3 Force Layout Variable Repulsive Foces

I am working on a Graph which has variable sized nodes: http://gordonsmith.github.io/Visualization/ (Click F2 to start the Force Layout)

Is it possible to change the repulsive forces based on node size at runtime? Basically I would like to "encourage" the layout to not have overlapping nodes...

Upvotes: 0

Views: 3016

Answers (1)

jshanley
jshanley

Reputation: 9138

The force layout allows you to pass a function to force.charge(), which would let you specify the charge strength for each node, being passed the node and its index as arguments.

If you were to create your nodes data in such a way that each element had an accessible property that represented its size (say the radius of a bounding circle), then you could use this data to set a relative charge value.

For example, if each element in your data had a property r representing its radius, you could do something like the following:

var force = d3.layout.force()
  .nodes(nodes)
  .size([width,height])
  .charge(function(d) {
    return -5 * d.r;
  })
  .on('tick', tick)
  .start();

The choice of a factor of -5 is completely arbitrary, and you will have to choose a value that works well for your data. Positive values represent attraction, and negative values represent repulsion.

HERE is a simple demo of this technique in action using circles.

Upvotes: 4

Related Questions