var svg = d3.select("body").append("svg")
...
var nodes = svg.append("circle")
.data(line.nodes);
line.nodes
是一个包含多个对象的数组,我想d3创建一个与每个对象绑定的圆。但是,上面的代码只创建一个圈,绑定到数据数组中的第一个对象。为什么这对数据数组中的其余对象来说不是相同的?了解D3选择
var svg = d3.select("body").append("svg")
...
var nodes = svg.append("circle")
.data(line.nodes);
line.nodes
是一个包含多个对象的数组,我想d3创建一个与每个对象绑定的圆。但是,上面的代码只创建一个圈,绑定到数据数组中的第一个对象。为什么这对数据数组中的其余对象来说不是相同的?了解D3选择
你需要告诉D3为不存在选择的所有元素创建节点。您可以使用selectAll
和enter
来完成此操作。阅读迈克·博斯托克的关于如何运作的细节以及幕后魔术的选择教程。 http://bost.ocks.org/mike/selection/
你会想沿着线代码:
var svg = d3.select("body").append("svg")
// Set some properties of your svg here
.attr("height", height)
.attr(...)
var nodes = svg.selectAll("circle")
//Bind the data to the selection
.data(line.nodes)
.enter().append("circle")
// Set attributes for the circles when D3 "enters" them.
.attr("r", myradius)
.attr(...)
这可能是最难在第一绕到你的头的部分是,你对尚不存在的元素调用selectAll
的事实。这是“数据绑定”的一部分。您将数据绑定到一个选区,D3将随着数据更改而创建,移除和更新元素。当您调用enter时,D3会为每个尚未拥有它们的数据成员创建元素,方法是使用append调用的元素和后面链接的属性。
绑定数据后应该调用.enter()
。
var svg = d3.select("body").append("svg")
var node = svg.selectAll(".circle");
node = node.data(graph.nodes)
.enter()
.append("circle")
.attr("cx", function(d){return d.x;})
.attr("cy", function(d){return d.y;})
.attr("r", 10)
选择'.circle'将查找类为'circle'的元素,而不是您追加的圆元素。 – danasilver
是的,你是对的。这是我从另一个项目中复制的一段代码,并且所有的圆圈都有这个类名。 – Parano