我一直在研究 D3JS 力布局图,但它并没有按预期工作。
我已将代码上传到 JSFiddle,可以在此处查看:
http://jsfiddle.net/jonaths/e9L3aq4k/
我认为它的重要部分如下,涉及更新节点/链接的阈值:
function threshold(thresh) {
graph.links.splice(0, graph.links.length);
for (var i = 0; i < graphRec.links.length; i++) {
if (graphRec.links[i].value > thresh) {
graph.links.push(graphRec.links[i]);
}
}
graph.nodes.splice(0, graph.nodes.length);
for (var j = 0; j < graphRec.nodes.length; j++) {
if (graphRec.nodes[j].value > thresh) {
graph.nodes.push(graphRec.nodes[j]);
}
}
restart();
}
//Restart the visualisation after any node and link changes
function restart() {
node = node.data(graph.nodes);
link = link.data(graph.links);
link.exit().remove();
node.exit().remove();
node.enter().insert("circle", ".node").attr("class", "node").attr("r", function (d) {
return d.value / 5
}).style("fill", "steelblue").call(force.drag);
link.enter().insert("line", ".node").attr("class", "link").call(force.drag);
force.start();
}
这个想法是,随着阈值的增加,不满足该阈值的节点和链接将被删除。当阈值随后更新时,应相应地添加/删除额外的链接/节点。
我使用了code here作为我想要做的事情的基础,但必须修改它以使节点消失,所以我的代码很可能存在问题。
现在我发现,如果你慢慢增加阈值,那么它就会完美地工作。但是,如果您只是将阈值单击到一个较高的值,然后再次更改它,则会出现一些奇怪的行为,导致图表损坏。您可能会注意到节点聚集在左上角。在控制台中查看输出会显示以下错误消息:
未捕获类型错误:无法读取未定义的属性“权重”
但我一生都无法弄清楚为什么有时会发生这种情况,但并非每次都会发生。我对 D3 相当陌生,所以任何帮助和建议将不胜感激,我希望我已经提供了所有必需的信息,以便有人给我一些指示。谢谢!
最佳答案
如果您在发生错误情况时检查数据,则会丢失指向其中一个节点的链接中的源
引用(它变为未定义):
[Object]
0: Object
source: undefined
target: Object
value: 75
__proto__: Object
length: 1
__proto__: Array[0]
我不确定为什么,但我重写了您的阈值函数以处理 d3
链接和节点对象(而不是返回源 json),并且它的行为符合预期:
var masterNodes = graph.nodes;
var masterLinks = graph.links;
function threshold(thresh) {
graph.nodes = [];
masterNodes.forEach(function(d,i){
if (d.value > thresh){
graph.nodes.push(d);
}
});
graph.links = [];
masterLinks.forEach(function(d,i){
if (d.value > thresh){
graph.links.push(d);
}
});
restart();
}
已更新fiddle .
关于javascript - d3js 强制布局未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28528422/