在使用d3.j中使用力布局时,可以通过增加围绕节点的假想半径来将节点推开。
我创建了一个名为button
的单独按钮,我想使用.data()
(选择一个整个数组)将碰撞半径增加到许多节点时的40个节点。例如,当将过滤数量的节点存储在名为abc
的数组中时,我尝试了此代码:
var node =......
.on("click", function(d, i) {
abc = start && start.path(d) || [];
node.style("fill", function(n) {
if (n == start ) {
return "yellow";
} else if ( n == d) {
return "green"
} else if (abc.includes(n)) {
return "red"
} else {
return "lightgrey"
}
.....
}});
button.on("click", function(d) {
d3.selectAll("circle").data().forEach(d => d.r = 6);
d3.select(abc).data().r = 40;
simulation.nodes(data);
simulation.alpha(0.8).restart();
})
我可以单击2个节点,然后存储这两个节点以及它们之间的所有节点在数组abc
中。借助D3.js函数path()
可以返回2个节点之间的最短方法。
但是不幸的是,它行不通。也许有人可以帮助我解决这个问题。在此处已经讨论了将节点推开的基本思想:将力量物理用于分开的元素非常感谢!
在几个评论之后,我终于对您如何过滤节点选择有所了解。
在以下演示中,圆圈具有4种不同的颜色:
var colours = ["blue", "red", "green", "yellow"];
node.attr("fill", (d, i) => colours[i%4]);
因此,当您单击按钮时,我们只需使用"红色"颜色过滤节点并增加其r
属性,从而使碰撞半径增加,使用each
:
node.filter(function() {
return d3.select(this).attr("fill") === "red"
}).each(d => d.r = 40);
如果您想将data
用作Getter,则可以使用forEach
:
node.filter(function() {
return d3.select(this).attr("fill") === "red"
}).data().forEach(d => d.r = 40);
具有相同结果。
这是一个演示,单击后,所有红色节点都会推开其他节点,碰撞半径为40:
var svg = d3.select("svg");
var colours = ["blue", "red", "green", "yellow"];
var data = d3.range(30).map(d => ({
r: 6
}));
var simulation = d3.forceSimulation(data)
.force("x", d3.forceX(150).strength(0.05))
.force("y", d3.forceY(75).strength(0.05))
.force("collide", d3.forceCollide(function(d) {
return d.r + 1;
}));
var node = svg.selectAll(".circles")
.data(data)
.enter()
.append("circle")
.attr("r", d => d.r)
.attr("fill", (d, i) => colours[i%4]);
d3.select("button").on("click", function(d) {
node.filter(function(){
return d3.select(this).attr("fill") === "red"
}).each(d=>d.r = 40);
simulation.nodes(data);
simulation.alpha(0.8).restart();
})
simulation.nodes(data)
.on("tick", d => {
node.attr("cx", d => d.x).attr("cy", d => d.y);
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<button>Click me</button>
<br>
<svg></svg>