使用多个连接组件时,D3 强制 v3 和 v4 之间的布局差异

D3 force layout differences between v3 and v4 when using mutliple connected components

MWE

我试图用两个版本创建相同的图表,这里是 Bl.ocks:

这些例子改编自 one 的官方例子。

问题

当有多个连通分量时,就会出现差异。在版本 4 中有两件事对我来说特别不起作用:

  1. 拖动一个连接的组件会使其他组件以一种非常非物理的方式疯狂地围绕(我猜)力中心平移;

  2. 在鼠标按下时(即使没有实际移动)其他连接的组件无限期地移动,最终离开屏幕。

简而言之,版本 3 中的图表 坚不可摧,无论您如何处理节点,它们最终都会 return 成为 稳定位置。

如何修复这两种行为,使模拟更类似于版本 3?

你不想要 d3.forceCenter。如果您查看 API:

The centering force translates nodes uniformly so that the mean position of all nodes (the center of mass if all nodes have equal weight) is at the given position ⟨x,y⟩

这意味着,当您将一个节点从中心移开时,其他节点将向相反方向移动,以补偿移动,因此质心保持不变在同一个位置。

而是使用 forceXforceY:

The x- and y-positioning forces push nodes towards a desired position along the given dimension with a configurable strength.

所以,这是模拟:

const simulation = d3.forceSimulation()
     .force('link', d3.forceLink().distance(200))
     .force('charge', d3.forceManyBody())
     .force('centerX', d3.forceX(width / 2))
     .force('centerY', d3.forceY(height / 2));

这是更新后的 fiddle:https://jsfiddle.net/ahdbLL8a/