d3.js 带有对象条目的 forceSimulation()

d3.js forceSimulation() with object entries


我的 气泡图 有问题。
我之前将 forceSimulation() 与一组对象一起使用并且它有效。现在我更改了数据源但它没有,即使控制台显示 no errors
我的数据是一个名为 "lightWeight" 的 object,具有以下结构:
我用它来附加圆圈,如下所示:

// draw circles
var node = bubbleSvg.selectAll("circle")
   .data(d3.entries(lightWeight))
   .enter()
   .append("circle")
   .attr('r', function(d) { return scaleRadius(d.value.length)})
   .attr("fill", function(d) { return colorCircles(d.key)})
   .attr('transform', 'translate(' + [w/2, 150] + ')');

然后我创建模拟:

// simulate physics
  var simulation = d3.forceSimulation()
    .nodes(lightWeight)
    .force("charge", d3.forceCollide(function(d) { return d.r + 10; }))
    .force("x", d3.forceX())
    .force("y", d3.forceY())
  .on("tick", ticked); // updates the position of each circle (from function to DOM)

  // call to check the position of each circle
   function ticked(e) {
      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
  }

但是圆圈仍然彼此重叠并且没有像以前那样变成气泡图。
如果这可能是一个愚蠢的问题,我深表歉意,我是 d3 的新手,对 forceSimulation() 的实际工作原理知之甚少。
例如,如果我用不同的数据多次调用它,生成的模拟是否只会影响指定的数据?
提前致谢!

这里有几个问题:

  1. 您正在使用 不同的 数据集进行渲染和力模拟,即:.data(d3.entries(lightWeight)) 创建一个 new 数组您用来绑定到 DOM 的对象,而 .nodes(lightWeight) 尝试 运行 对原始 lightWeight 对象的力模拟(它需要一个数组,所以这不是去上班)。

尝试在任何此代码开始之前执行类似 var lightWeightList = d3.entries(lightWeight); 的操作,并使用该数组绑定到 DOM 并作为力模拟的参数。当然,这应该清楚地表明,当涉及到 更新 您正在查看的节点时,您可能 运行 遇到其他挑战——覆盖 lightWeightList 会造成破坏任何先前的节点位置(因为我们看不到您的更多代码,尤其是 如何 您会第二次调用它,我没有任何有用的想法)。

  1. 特别是如果您打算重新调用此代码,还有一个问题:您链接 .enter() 调用的方式意味着 node 将仅引用 enter selection——这意味着,如果您再次调用此代码,力模拟只会更新 ticked.[=37= 内的 new 节点]

对于 D3,我发现一个好习惯是将您的选择保存在单独的变量中,例如:

var lightWeightList = d3.entries(lightWeight);

// ...

var nodes = bubbleSvg.selectAll('circle')
  .data(lightWeightList);
var nodesEnter = nodes.enter()
  .append('circle');
// If you're using D3 v4 and above, you'll need to merge the selections:
nodes = nodes.merge(nodesEnter);
nodes.select('circle')
     .attr('r', function(d) { return scaleRadius(d.value.length)})
     .attr('fill', function(d) { return colorCircles(d.key)})
     .attr('transform', 'translate(' + [w/2, 150] + ')');

// ...

var simulation = d3.forceSimulation()
  .nodes(lightWeightList)
  .force("charge", d3.forceCollide(function(d) { return d.r + 10; }))
  .force("x", d3.forceX())
  .force("y", d3.forceY())
  .on("tick", ticked);

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