d3.js 圆圈没有出现

pra*_*432 4 javascript d3.js

我正在学习本教程

http://flowingdata.com/2012/08/02/how-to-make-an-interactive-network-visualization/

我正在尝试让更新节点正常工作(我的数据略有不同)。

var updateNodes = function(nodes){
console.log("updateNodes Called");
console.log(nodes);
var node = nodesG.selectAll("circle.node").data(nodes,function(d){
    return d.id;
});
node.enter().append("circle").attr("class","node")
.attr("cx",x)
.attr("cy",y)
.attr("r",1000)
.style("fill","steelblue")
.style("stroke","black")
.style("stroke-width",1.0);

node.exit().remove();   
Run Code Online (Sandbox Code Playgroud)

}

这不会使任何圆圈出现在 DOM 上。

节点G定义为:

var nodesG = d3.selectAll("g");
Run Code Online (Sandbox Code Playgroud)

这个函数是从

var update = function(){

force.nodes(data.nodes);
updateNodes(data.nodes);

//force.links(curLinksData);
//updateLinks();


//force.start();
Run Code Online (Sandbox Code Playgroud)

}

为什么什么都没有出现?

谢谢,

Chr*_*che 6

在您的代码中不起作用的第一件事是您没有创建将svg在其中绘制圆圈的元素。所以你必须更换

    var nodesG = d3.selectAll("g");
Run Code Online (Sandbox Code Playgroud)

经过

    var nodesG = d3.select('body').append('svg');
Run Code Online (Sandbox Code Playgroud)

然后,您没有很好地定义圈子的属性 x 和 y。我猜这些属性取决于每个节点的属性x和属性y。因此,您必须替换以下内容:

    .attr("cx", x)
    .attr("cy", y)        
Run Code Online (Sandbox Code Playgroud)

经过:

    .attr("cx", function(d){return d.x})
    .attr("cy", function(d){return d.y})
Run Code Online (Sandbox Code Playgroud)
  • 最后,您必须update()在脚本末尾调用

这是一个有效的 jsFiddle:http : //jsfiddle.net/chrisJamesC/S6rgv/