【问题标题】:D3 force layout nodes attributes not updated properlyD3 强制布局节点属性未正确更新
【发布时间】:2014-05-23 18:45:59
【问题描述】:

我有不同日期的网络数据,我将这些数据绘制为每一天的力导向图。当我按下按钮时,网络部分(删除节点,绘制新节点)更新到第二天。一切正常,除了一件事。

对于每一天,我都会根据我的数据更新我的节点数组的一些属性(例如节点的度数)。这也可以正常工作,因为当我切换到第二天后查看节点数组时,我可以看到属性已正确更新。但是命令

     `.append("circle").attr("r", function(d) { return 2*d.Degree+10; })`

不使用新属性进行,节点半径不以图表显示日期的节点度数表示。

如何更新我的图表,以便使用 Degree 的新值来定义节点的半径?

这是我的函数 start(),我在处理数据以绘制图形后调用它:

function start() {

var force = d3.layout.force()
    .charge(-130)
    .linkDistance(230)
    .size([width, height]);

force.nodes(nodes)
    .links(edges)

linkOP = linkOP.data(edges, function(d) { return d.source.id + "-" + d.target.id; });
linkOP.enter().insert("line", ".node1")
    .attr("class", "link1")
    .style("stroke-width", function(d) {
        return 2*d.weight.weight;
      });
linkOP.exit()
    .remove();

nodeOP = nodeOP.data(nodes, function(d) { return d.id;});
nodeOP.enter()  
    .append("g")
    .append("circle")
    .attr("r",   function(d) { return 2*d.Degree+10; })
    .attr("class", "node")
    .style("fill", function(d) { return color(d.bipartite); });

nodeOP.append("title").text(function(d) { return d.name; });
nodeOP.call(force.drag);
nodeOP.append("text")
    .text(function(d) { return d.id; });
nodeOP.moveToFront();
nodeOP.exit().remove();

force.start();

clean();

force.on("tick", function() {
    linkOP.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

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

    nodeOP.attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";
    });

});

}

我知道这是一个非常简单的问题...非常感谢您的帮助!

【问题讨论】:

    标签: javascript d3.js force-layout


    【解决方案1】:

    您的代码没有更新半径。 .enter() 调用的所有内容只发生在新项目上。所以因为你只有这条线

    .append("circle").attr("r", function(d) { return 2*d.Degree+10; })`
    

    在 .enter 中,该部分仅出现在新节点上。

    我在进入、更新、退出时构建了一个 jsfiddle。这里:http://jsfiddle.net/TheMcMurder/H3HTe/

    希望对你有帮助

    【讨论】:

    • 嘿伙计,非常感谢您的快速回复。根据您的示例,我添加了: 'var node_array = svg1.selectAll("circle").data(nodes, function(d) { return d.id;}); node_array.attr("r", function(d) { return 2*d.Degree+10; });'行前:'nodeOP = nodeOP.data(nodes, function(d) { return d.id;});'在我的启动功能中。现在我看到未更新节点的大小正在发生变化,但仍然没有使它们代表分配给它们的属性。这对我来说很奇怪,因为当我在浏览器中查看 nodeOP-array 时,所有属性都已正确定义。
    • 发现我的错误!非常感谢,祝你周末愉快(你真的解决了这个问题,这很适合你的名字!)。 Stackoverflow 规则!
    猜你喜欢
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2014-10-24
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多