我是 javascript/d3 的初学者,遇到了一个很棒的 network visualization我想玩玩。
我希望通过在指定时间添加链接及其关联节点来使可视化变得动态。
为了让我开始,我首先尝试保持所有节点的显示,并简单地添加数据文件中出现的链接。
剥离original html文件,这是我的尝试(添加 iterateLink() 函数,并稍微调整initializeGraph()):
function iterateLinks() {
for ( x = 0; x < zlinkz.length; x++ ) {
setTimeout( function() {
links.push(zlinkz[x]);
restart();
}, 2000);
}
}
function initializeGraph(newGraph) {
newNodes = [];
newLinks = [];
// We need a hash to fit the link structure of D3's force-directed layout
nodeHash = {};
zlinkz = [];
for ( x = 0; x < newGraph.nodes.length; x++ ) {
newNodes.push(newGraph.nodes[x]);
nodeHash[String(newGraph.nodes[x].id)] = x;
}
for ( x = 0; x < newGraph.links.length; x++ ) {
newLinks.push({id: x, source: newGraph.nodes[nodeHash[newGraph.links[x].source]], target: newGraph.nodes[nodeHash[newGraph.links[x].target]], "cost": newGraph.links[x].cost, "weight": newGraph.links[x].invcost });
}
force = d3.layout.force()
.size([width, height])
.nodes(newNodes) // initialize with a single node
.links(newLinks)
.linkDistance(60)
.charge(-60)
.on("tick", tick);
var svg = d3.select("#viz").append("svg")
.attr("width", width)
.attr("height", height)
.attr("id", "networkViz");
svg.append("rect")
.attr("width", width)
.attr("height", height)
.attr("id","backgroundRect")
.on("mousemove", mousemove);
nodes = force.nodes();
links = force.links();
node = svg.selectAll(".node");
link = svg.selectAll(".link");
arrowhead = svg.selectAll(".link");
cursor = svg.append("circle")
.attr("transform", "translate(-100,-100)")
.attr("class", "cursor")
.attr("r", 1)
.style("opacity", 0);
restart();
iterateLinks();
}
完整代码可以在jsfiddle上找到.
尽管我使用了 iterateLinks() 函数,但该函数似乎并未迭代链接,并且不显示链接。
你知道我的函数哪里出了问题以及如何解决吗?
非常感谢任何帮助! 谢谢。
=====编辑=====
感谢@Barnab 和@AmeliaBR 的帮助,我做出了更改here并且还包括动态添加节点。
最佳答案
几件事:
在
iterateLinks
中,x
变量在调用setTimeout
中的函数之前从 0 变为 2,导致始终推送zlinkz[3]
而不是您想要的 0 到 2 范围。我用这种方式修复了它,它的工作方式可能是您想要的:var it = 0; for (x = 0; x < zlinkz.length; x++) { setTimeout(function () { links.push(zlinkz[it]); restart(); it++; }, 2000); }
您的
箭头
绘图似乎有问题。我在这个更新的jsfiddle中注释掉了它如果我理解它的功能是什么,我也许可以帮助您调试它:)如果您取消注释,您会看到连接的链接和节点由于.getElementById('directedCheck').checked 问题而消失
PS:我在my blog上写了一篇关于动态力布局可视化的教程。也许它可以为您 future 的努力提供一些想法。
关于javascript - 迭代地将链接附加到 D3 力定向网络可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663454/