Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 44 ยท Layouts and Hierarchies

Force-Directed Graphs

Build a draggable force-directed network graph with d3.forceLink, node sizing by degree, colored groups, labels and hover highlighting of neighbors.

A network (or graph) is a set of nodes and the links between them: friendships, citations, dependencies between packages, road junctions. A force-directed graph lets a simulation find a readable arrangement: links act as springs pulling connected nodes together while all nodes repel one another. If you have not met the simulation yet, start with Force Simulations.

Data shape

The usual JSON format is two arrays:

JavaScript
const graph = {
  nodes: [{ id: "Ana", group: 1 }, { id: "Ben", group: 1 }, { id: "Cy", group: 2 }],
  links: [{ source: "Ana", target: "Ben" }, { source: "Ben", target: "Cy" }]
};

d3.forceLink(links).id(d => d.id) tells D3 to look up nodes by their id. Without .id() it expects source and target to be numeric indexes into the nodes array. After the first tick D3 replaces the id strings in each link with the actual node objects, so link.source.x becomes valid. Always copy your data first (links.map(d => ({...d}))) if you want to keep the original.

Setting Meaning
.distance(d => 40) the length the spring wants (default 30)
.strength(0.5) how hard it pulls toward that length (default depends on node degree)
.iterations(2) more iterations make links stiffer but cost time

A typical combination is forceLink plus a negative forceManyBody and a forceCenter. Add forceCollide when nodes have sizes.

A complete interactive graph

Draggable network

Drag any node: the rest of the graph follows because the simulation is heated up while you drag and cools afterward.

How the drag works

d3.drag() emits start, drag and end events with the event object first and the node's datum second (D3 v6 and later). The recipe has three steps:

  1. On start, if no other drag is active (!event.active) raise the target alpha so the simulation runs, and pin the node where it is.
  2. On drag, copy the pointer position event.x, event.y into d.fx and d.fy.
  3. On end, lower the alpha target and release the node (or keep fx/fy set if you want dragged nodes to stay put).

Sizing, colour and labels

  • Size by degree (number of links), as above, shows hubs at a glance. Compute degree once from the links array.
  • Colour by group with an ordinal scale. For communities you would first run a clustering algorithm on the server and save the group id into the data.
  • Labels: put text in the same <g> as the circle so both move together. For large graphs show labels only for the biggest nodes or on hover.

Highlighting neighbors

A frequent request is "highlight a node and its neighbours on hover". Build a set of connected ids once and use classes:

JavaScript
const neighbors = new Map(nodes.map(n => [n.id, new Set([n.id])]));
links.forEach(l => {
  neighbors.get(l.source.id ?? l.source).add(l.target.id ?? l.target);
  neighbors.get(l.target.id ?? l.target).add(l.source.id ?? l.source);
});

node.on("mouseenter", (event, d) => {
  node.style("opacity", n => neighbors.get(d.id).has(n.id) ? 1 : 0.2);
  link.style("opacity", l => (l.source === d || l.target === d) ? 1 : 0.1);
}).on("mouseleave", () => {
  node.style("opacity", 1);
  link.style("opacity", 1);
});

The ?? fallback handles both states of a link: before the first tick source is an id string, afterwards a node object.

Performance for larger graphs

SVG handles a few hundred nodes well. Beyond about 2000 elements, tick updates become expensive. Options:

  • Draw on <canvas> instead (see Canvas rendering and performance); the simulation code stays identical.
  • Use forceManyBody().theta(0.9) and .distanceMax(300) to make repulsion cheaper.
  • Precompute the layout with sim.stop(); sim.tick(300) and draw the result once.
  • Reduce alphaDecay only if you need smoother settling; larger values finish sooner.
flowchart LR
  A["JSON: nodes + links"] --> B["forceSimulation(nodes)"]
  B --> C["forceLink resolves ids to node objects"]
  C --> D["tick: update line and group positions"]
  D --> E["drag: fx and fy pin a node"]
  E --> B

Dragging feeds back into the simulation, so the whole graph reacts.

Common mistakes

  • Links that refer to ids not present in the nodes array: D3 throws node not found: X. Check your data.
  • Reusing the same links array for a second simulation: the first one already replaced ids with objects.
  • Making the repulsion too weak (for example -5) so the graph collapses into a ball, or too strong so nodes fly out of the SVG. Start around -100 to -300 and tune.
  • Using .on("drag", function(event, d)) with the pre-v6 signature (d); the event now comes first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does .id(d => d.id) on forceLink do?

    Links refer to nodes by id; the accessor tells D3 which property of a node holds that id.
  2. 2. After the simulation has started, what is link.source?

    forceLink replaces the ids with references to the node objects so you can read source.x and source.y.
  3. 3. Why do we call sim.alphaTarget(0.3).restart() when a drag starts?

    A cooled simulation does not move. Raising the alpha target keeps forces active during the drag.
  4. 4. What is a good option for graphs with thousands of nodes?

    Canvas avoids creating thousands of DOM elements; the same simulation can drive it.

Summary

  • A graph is a nodes array plus a links array; forceLink with .id() connects them.
  • Combine link, many-body, center and collide forces.
  • d3.drag plus fx/fy and alphaTarget gives smooth dragging.
  • Size nodes by degree, colour by group, and highlight neighbours with a precomputed map.
  • Switch to canvas when the graph gets big.

Next: Chord Diagrams and Binning