我已经使用d3创建了一个强制布局,并且效果很好。我最初的数据是从JSON文件加载和图表绘制类似于this d3.js example技术:在d3 Force Layout中更新现有节点
现在,该图是我需要补充,更新和删除节点上的屏幕上从我通过网络套接字接收的数据飞行。我有添加和删除方法的工作,但我找不到更新现有节点的属性的正确方法。
从我所进行的阅读中我收集了正确的技术是更改数据源,然后使用enter()方法更新图表。
要更新我在做一个节点如下:
function updateNode(id, word, size, trend, parent_id){
var updateNode = nodes.filter(function(d, i) { return d.id == id ? this : null; });
if(updateNode[0]){
updateNode.size = Number(size);
updateNode.trend = trend;
nodes[updateNode.index] = updateNode;
update();
}
}
然后更新功能与更新的节点:
function update(){
node = vis.selectAll('.node')
.data(nodes, function(d) {
return d.id;
})
createNewNodes(node.enter());
node.exit().remove();
force.start();
}
function createNewNodes(selection){
var slct = selection.append('g')
.attr('class', 'node')
.call(force.drag);
slct.append('circle')
.transition()
.duration(500)
.attr('r', function(d) {
if(d.size){
return Math.sqrt(sizeScale(d.size)*40);
}
})
}
我是否采取正确的方法呢?当我尝试这段代码时,我试图在圆上设置radius属性时获得的节点是节点数组中的最后一个节点。即包含分层节点数据而不是单个节点对象的数据库。
任何指针将不胜感激,我已经花了太多时间在这:)
我有同样的问题,虽然在一个更简单的环境。你找到解决方案吗? – 2013-03-01 14:27:53
可以把你的代码放到在线编辑器中,例如http://phrogz.net/JS/d3-playground/#BlankDefault – ppoliani