D3 单节点加力

D3 adding force to single node

我使用 D3 的力布局制作了一个分组气泡图,以创建一个朝向中间的力,如下所示:

  var forceStrength = 0.03;
  var center = { x: widthBubbles / 2, y: heightBubbles / 2 };

  var simulation = d3.forceSimulation()
     .velocityDecay(0.2)
     .force('x', d3.forceX().strength(forceStrength).x(center.x))
     .force('y', d3.forceY().strength(forceStrength).y(center.y))
     .force('charge', d3.forceManyBody().strength(charge))
     .on('tick', ticked);

  function charge(d) {
    return -forceStrength * Math.pow(d.r, 2.0);
  }

  function ticked() {
    bubbles
      .attr('cx', function (d) { return d.x; })
      .attr('cy', function (d) { return d.y; });
  }

我的图表看起来与此类似:Gates Foundation Educational Spending

我希望能够在单击单个节点时对其施加力,以便单击的节点移动到另一个区域。在 D3 的文档中有一个叫做 "positioning forces" 的东西,根据文档,它旨在用于多个节点:

While these forces can be used to position individual nodes, they are intended primarily for global forces that apply to all (or most) nodes.

所以我的问题是是否有一种方法可以对 D3 中的单节点施加力。

我通过创建一个函数解决了这个问题,每次点击气泡时都会调用该函数:

  //Function for moving bubbles when selected
  function moveSelectedBubbles() {
    simulation.force('x', d3.forceX().strength(forceStrength).x(function(d){
      //Check if bubble is selected
      return (selectedCountries.indexOf(d.data.country) >= 0) ? selectedCenter.x : center.x;
    }));

  simulation.alpha(1).restart();

  }

但是这个函数在每次选择气泡时设置每个节点的力。也许有更有效的方法来处理此案。