https://observablehq.com/@d3/force-directed-graph I'm trying to understand this code in order to figure out how d3-force works.
I trace the variable nodes
to see how they assign position to them.
// Replace the input nodes and links with mutable objects for the simulation.
console.log(nodes); // Added by me
nodes = d3.map(nodes, (_, i) => ({id: N[i]}));
console.log(nodes); // Added by me
links = d3.map(links, (_, i) => ({source: LS[i], target: LT[i]}));
Somehow the variable nodes
after d3.map
has all the variables needed for forceSimulation, including index
, x
, y
, vx
, vy
.
I think this has more to do with how javascript execute the functions below it than d3 itself, but I don't know how.
I also printed N
but there's nothing special about it. Just the id
value, as expected from the previous code.
CodePudding user response:
Those properties you mentioned are created by the simulation itself, after you pass the nodes to the simulation.
As the documentation states,
Each node must be an object. The following properties are assigned by the simulation:
- index - the node’s zero-based index into nodes
- x - the node’s current x-position
- y - the node’s current y-position
- vx - the node’s current x-velocity
- vy - the node’s current y-velocity
When you first log the nodes, they do not have those properties. However, after the simulation runs, those properties will show up on the object already logged on the console. In Chrome, for instance, you'll see a blue icon saying something like "the object below was evaluated just now". If you do console.log(JSON.stringify(nodes))
instead of console.log(nodes)
you'll see the original object.