Bli*_*ank 13 javascript graph d3.js
我json从数据库加载并创建一个json加载正常的文件.现在我不知道在Force-Directed Graph中使节点响应的步骤.我需要删除并添加新节点及其链接.
force.nodes(json.nodes)
.links(json.links)
.start();
initNodes(json);
Run Code Online (Sandbox Code Playgroud)
如何在不重置整个可视化的情况下使其更加动态或更新?
我已经看过几次没有回答这个问题,所以我希望有人可以发帖并给出指导.
Wal*_*man 14
添加节点/链接到我的D3力图非常混乱,直到我更好地理解我添加初始节点集的方式.
假设a <g>是您要用于节点的内容:
// Select the element where you'd like to create the force layout
var el = d3.select("#svg");
// This should not select anything
el.selectAll("g")
// Because it's being compared to the data in force.nodes()
.data(force.nodes())
// Calling `.enter()` below returns the difference in nodes between
// the current selection and force.nodes(). At this point, there are
// no nodes in the selection, so `.enter()` should return
// all of the nodes in force.nodes()
.enter()
// Create the nodes
.append("g")
.attr("id", d.name)
.classed("manipulateYourNewNode", true);
Run Code Online (Sandbox Code Playgroud)
现在让我们创建一个函数,一旦图形初始化,它将为布局添加一个节点!
newNodeData是一个对象,包含您要用于新节点的数据.
connectToMe是一个字符串,包含您要将新节点连接到的节点的唯一ID.
function createNode (newNodeData, connectToMe) {
force.nodes().push(newNodeData);
el.selectAll("g")
.data(force.nodes(), function(datum, index) { return index })
Run Code Online (Sandbox Code Playgroud)
作为可选的第二个参数in给出的函数.data()对于选择中的每个节点运行一次,并且对于每个节点再次运行force.nodes(),根据返回的值对它们进行匹配.如果没有提供函数,则调用回退函数,该函数返回index(如上所述).
但是,新选择的索引(我相信订单是随机的)和订单中的订单很可能会出现争议force.nodes().相反,您很可能需要该函数来返回每个节点唯一的属性.
这次,.enter()只会返回您尝试添加的节点,newData因为第二个参数没有找到任何键.data().
.enter()
.insert("g", "#svg")
.attr("id", d.name)
.classed("manipulatYourNewNode", true);
createLink(connectToMe, newNodeData.name);
force.start();
}
Run Code Online (Sandbox Code Playgroud)
createLink函数(在下面定义)在您的新节点和您选择的节点之间创建一个链接.
此外,d3js API声明在更新布局后应调用force.start().
注意:force.stop()当我第一次尝试找出如何添加节点和链接到我的图表时,在函数的最开始时调用对我来说是一个巨大的帮助.
function createLink (from, to) {
var source = d3.select( "g#" + from ).datum(),
target = d3.select( "g#" + to ).datum(),
newLink = {
source: source,
target: target,
value: 1
};
force.links().push(newLink);
Run Code Online (Sandbox Code Playgroud)
以下代码在以下假设下运作:
#links 是包含所有链接元素的包装元素 您的链接表示为<line>元素:
d3.select("#links")
.selectAll("line")
.data(force.links())
.enter()
.append("line");
Run Code Online (Sandbox Code Playgroud)您可以在此处查看如何附加新节点和关系的示例:http: //bl.ocks.org/2432083
摆脱节点和关系有点棘手,但你可以在这里看到这个过程:http: //bl.ocks.org/1095795