我正在从数据库加载json并创建一个加载正常的json文件。现在,我不知道应该采取哪些步骤来使节点在力定向图中做出响应。我需要删除和添加新节点及其链接。
force.nodes(json.nodes)
.links(json.links)
.start();
initNodes(json);如何在不重置整个可视化的情况下使其更具动态性或进行更新?
这个问题我已经看过几次了,没有人回答,所以我希望有人能发帖并给予指导。
发布于 2013-08-17 08:13:55
向我的D3力图添加节点/链接非常令人困惑,直到我更好地理解了添加初始节点集的方式。
假设您想要为节点使用<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);现在,让我们创建一个函数,该函数将在初始化图形后向布局中添加一个节点!
newNodeData是一个对象,其中包含要用于新节点的数据。connectToMe是一个字符串,其中包含要将新节点连接到的节点的唯一id。
function createNode (newNodeData, connectToMe) {
force.nodes().push(newNodeData);
el.selectAll("g")
.data(force.nodes(), function(datum, index) { return index })对于选择中的每个节点和force.nodes()中的每个节点,作为.data()中的可选第二个参数给出的函数运行一次,并根据返回值对它们进行匹配。如果没有提供函数,则调用一个回退函数,该函数返回index (如上所述)。
然而,新选择的索引(我相信顺序是随机的)和force.nodes()中的顺序之间很可能存在争议。相反,您很可能需要该函数来返回每个节点唯一的属性。
这一次,.enter()将只返回您试图添加为newData的节点,因为.data()的第二个参数没有找到该节点的键。
.enter()
.insert("g", "#svg")
.attr("id", d.name)
.classed("manipulatYourNewNode", true);
createLink(connectToMe, newNodeData.name);
force.start();
}函数createLink (定义如下)在新节点和所选节点之间创建链接。
另外,the d3js API states that force.start() should be called after updating the layout。
注意:当我第一次试图弄清楚如何向我的图形添加节点和链接时,在我函数的最开始调用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);下面的代码在以下假设下工作:
#links是包含所有链接元素的包装器元素<line>元素:.append("line"); (“#links”).selectAll(“.data”) .data(force.links()) .enter() .enter()行
https://stackoverflow.com/questions/11606214
复制相似问题