这里有几个问题:
-
您正在使用
不同的
用于渲染和力模拟的数据集,即:
.data(d3.entries(lightWeight))
新
用于绑定到DOM的对象数组,而
.nodes(lightWeight)
lightWeight
对象(它需要一个数组,所以这行不通)。
尝试这样做
var lightWeightList = d3.entries(lightWeight);
正在更新
您正在查看哪些节点正在重写
lightWeightList
怎样
-
特别是如果您计划重新调用此代码,还有一个问题:链接
.enter()
通话意味着
node
将仅参考
进来
选择意味着,如果再次调用此代码,力模拟只会更新
新
ticked
.
对于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; });
}