liveBook · Manning

forceX

As explained in D3.js in Action, Third Edition

d3.forceX() creates a D3 force that attracts nodes toward a specified horizontal position.

`d3.forceX()` pulls nodes toward a horizontal position in a D3 force simulation. For example, `forceX(0)` draws nodes toward x = 0 while leaving them loosely spread along the y-axis. Pair it with `forceY(0)` and both forces draw nodes toward (0, 0). section 12.4.1

Use `.strength()` to adjust the pull. Its default is 1; reducing the x-force strength to 0.01 while retaining `forceY(0)` makes horizontal attraction weaker than vertical attraction. A position can also come from a scale, giving different groups distinct targets. section 12.4.1

Position values in a beeswarm

Add `.force("x", forceX(d => xScale(d.value)))` to position each node horizontally by its value. Combine it with `forceY(0)` and `forceCollide().radius(7)` to form a beeswarm plot whose circles do not overlap. section 12.4.1

forceSimulation()
  .force("x", forceX(d => xScale(d.value)) )
  .force("y", forceY(0) )
  .force("collide", forceCollide().radius(7) )
  .nodes(sampleNodes)
  .on("tick", updateNetwork);

See how the x-force, y-force, and collision force are registered together in a working simulation. section 12.4.1

How D3.js in Action, Third Edition covers it

How deep it goes
Works through target positions, relative strength, scale-driven targets, and combinations with other forces.
Examples
Shows nodes attracted to x = 0 and values positioned with an x-scale in a beeswarm.
What you can do after
Apply it via D3 to set horizontal targets and tune their attraction in a force simulation.
How it connects
Connects force simulations with forceY, forceCollide, point scales, and beeswarm plots.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.