Three.js Force-Directed Network Graph (3D)

An interactive force-directed network graph in Three.js, laying out hundreds of nodes from a community-structured random graph with Coulomb repulsion, spring links and cooling, sized by degree, coloured by community, with neighbour highlighting on hover.

Key topics: force directed graph, network visualization, three.js graph, node link diagram, community detection, 3d graph

What this code does

- Graph Model: a stochastic block model with preferential attachment gives dense communities, sparse bridges and a few hubs.
- Forces: every pair repels (∝ 1/d²), every edge is a spring toward its rest length, and weak gravity keeps the layout centred.
- Cooling: a temperature (alpha) scales the forces and decays each step so the layout settles; Reheat shakes it up again.
- Encoding: node size is √degree, colour is community, and grey edges cross between communities.
- Interaction: hovering a node raycasts the InstancedMesh and dims everything except its direct neighbours.
- Controls: node and community counts, repulsion, spring length, centring, 2D/3D layout, simulate and reheat.

Continue Learning

JavaScript Implementation

ES6+
// Force-directed graph layout: repel all nodes, pull linked nodes together, cool over time

function step () {
  for (const a of nodes) {
    for (const b of nodes) if (a !== b) {
      const d = a.pos.clone().sub(b.pos); const r2 = d.lengthSq() + 0.01
      a.vel.addScaledVector(d, repulsion * alpha / (r2 * Math.sqrt(r2)))     // Coulomb
    }
  }
  for (const { source, target } of links) {
    const d = target.pos.clone().sub(source.pos); const len = d.length()
    d.multiplyScalar((len - restLength) * 0.06 / len)                       // Hooke
    source.vel.add(d); target.vel.sub(d)
  }
  nodes.forEach(n => n.pos.add(n.vel.multiplyScalar(0.85)))                 // damping
  alpha *= 0.995
}