节点 x 和 y 是否自动设置在强制布局图中?

Are node x and y automatically set in force layout graphs?

this bl.ocks d3 example中,节点如何获得它们的随机"cx"和"cy"属性? (他们的 x 和 y 位置)?他们是随机分配的吗?

我看到的唯一分配节点的 cx 和 cy 的代码是下面的行(在示例代码的底部):

 node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

但是,无论是在数据中还是在代码的其他任何地方,我都没有看到 d.xd.y 的定义。他们是如何设置的?

强制布局设置值。您正在将布局连接到此处的数据:

force
  .nodes(graph.nodes)
  .links(graph.links)
  .start();

来自 documentation(强调我的):

force.nodes([nodes])

If nodes is specified, sets the layout's associated nodes to the specified array. If nodes is not specified, returns the current array, which defaults to the empty array. Each node has the following attributes:

  • index - the zero-based index of the node within the nodes array.
  • x - the x-coordinate of the current node position.
  • y - the y-coordinate of the current node position.
  • px - the x-coordinate of the previous node position.
  • py - the y-coordinate of the previous node position.
  • fixed - a boolean indicating whether node position is locked.
  • weight - the node weight; the number of associated links.

These attributes do not need to be set before passing the nodes to the layout; if they are not set, suitable defaults will be initialized by the layout when start is called. However, be aware that if you are storing other data on your nodes, your data attributes should not conflict with the above properties used by the layout.