Force directed graph: custom forces

There’s two types of forces in the d3-force module – preshipped forces and custom forces.

Preshipped forces have already been written for you. Custom forces you write yourself.

Here we’ll cover custom forces.

What is a custom force? Link to heading

A custom force is simply a function that modifies the positions and velocities of nodes.  See the d3 API.

You write custom forces to achieve effects that aren’t possible by using the preshipped forces.

Perhaps you want to impose a geometric constraint, like making sure nodes are bound inside a svg box.  You’d use a custom force.

Or maybe you want to utilise your node and link attributes to change the sizes of some nodes over time. You’d use a custom force.

Custom forces are really flexible things.

Structure of a custom force Link to heading

A very basic custom force could look like the following code snippet. In the following I assume your nodes data is stored under the variable nodes_data:

function splitting_force() { 
  for (var i = 0, n = nodes_data.length; i < n; ++i) {
    curr_node = nodes_data[i];
    // do things here to change the position and velocity of curr_node
    // position is curr_node.x, curr_node.y
    // velocity is curr_node.vx, curr_node.vy
  }
}

This function loops through the nodes one by one. You’d put in code in the commented section to change the position and velocity of the nodes.

Another thing you can do is pass in the simulation’s alpha value from the forceSimulation as a parameter. You’d then use alpha as part of your logic for determining node positions on each tick.

function splitting_force(alpha) { 
  for (var i = 0, n = nodes_data.length; i < n; ++i) {
    curr_node = nodes_data[i];
    // do things here to change the position and velocity of curr_node
    // position is curr_node.x, curr_node.y
    // velocity is curr_node.vx, curr_node.vy
    // use alpha as well!
  }
}

Examples Link to heading

Click through the following examples to see custom forces in action.


Hope you found that useful! Click here to view to the rest of the force directed graph series.