如何在底层数据更改时更新D3强制布局的元素 [英] How to update elements of D3 force layout when the underlying data changes

查看:274
本文介绍了如何在底层数据更改时更新D3强制布局的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用强制布局示例之一( http://bl.ocks.org/1153292)在我的网站上显示网络。



我允许用户选择在任何给定时间看到的链接类型。我注意到,当我选择看到链接类型A,然后添加链接类型B,然后删除链接类型A的类型B的剩余链接呈现A颜色。



这是运行以添加到svg图的链接的代码。我通过添加和删除链接来更改数组 this.links 。你可以看到我设置类的属性,但它不更新 - 它仍然是链接A的类型。

  var path = svg.append(svg:g)
.selectAll(path)
.data(this.links)
.enter()
.append(svg:路径)
.attr(class,function(d){returnlink+ d.type;})
.attr(marker-end,function(d){return url(#+ d.type +);});

我目前通过更新tick函数中的class属性来解决这个问题,不需要的工作。



我读取enter操作返回一个合并选择的存在元素和新的,所以attr操作应该更新存在的和设置

解决方案

我发现了此帖中的回答

  var circle = svg.selectAll(circle)
.data(data);

circle.enter()。append(circle)
.attr(r,2.5);

circle
.attr(cx,function(d){return dx;})
.attr(cy,function(d){return dy;} );

circle.exit()。remove();

答案是我需要在selectAll.data的结果上调用attr运算符,附加操作符的结果。


I'm using one of the force layout examples (http://bl.ocks.org/1153292) to show a network on my web site.

I allow the user to choose which type of links to see at any given time. I notice that when I choose to see link type A, then add link type B and then remove link type A the remain links of type B are presented with A colors.

This is the code that runs to add the links to the svg diagram. I am changing the array this.links by adding and removing links from it. As you can see I set the class attribute but it is not updating - it remains of type of link A.

var path = svg.append("svg:g")
    .selectAll("path")
    .data(this.links)
   .enter()
    .append("svg:path")
    .attr("class", function(d) { return "link " + d.type; })
    .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });

I currently work around this problem by updating the class attribute inside the tick function but this off course cause much un-needed work.

I read that the enter operation return a merged selection of the exist elements and also the new ones so the attr operation should update the exist one and set the new one.

What am I missing?

解决方案

I've found the answer in this post

var circle = svg.selectAll("circle")
    .data(data);

circle.enter().append("circle")
    .attr("r", 2.5);

circle
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; });

circle.exit().remove();

The answer is that I need to call attr operator on the result of selectAll.data and not on the result of the append operator.

这篇关于如何在底层数据更改时更新D3强制布局的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆