简体   繁体   English

了解d3选择

[英]understanding d3 selections

var svg = d3.select("body").append("svg")
 ...
var nodes = svg.append("circle")
.data(line.nodes);

line.nodes is an array that contains several objects, and I want d3 to create a circle bound to each of those objects. line.nodes是一个包含多个对象的数组,我希望d3创建一个绑定到每个对象的圆。 However, the code above is only creating one circle, bound to the first object in the data array. 但是,上面的代码只创建一个圆,绑定到数据数组中的第一个对象。 Why is this not doing the same for the rest of the objects in the data array? 为什么这对数据数组中的其余对象没有做同样的事情?

You should call .enter() after binding the data. 绑定数据后应调用.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)

You need to tell D3 to create nodes for all elements of the selection that don't already exist. 您需要告诉D3为选择中尚不存在的所有元素创建节点。 You can do this with selectAll and enter . 您可以使用selectAll执行此操作并enter Read Mike Bostock's tutorial on selections for the details of how this works and the real magic behind the scenes. 阅读Mike Bostock关于选择的教程,了解其工作原理以及幕后真正的魔力。 http://bost.ocks.org/mike/selection/ http://bost.ocks.org/mike/selection/

You'll want code along the lines of: 您将需要以下代码:

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(...)

The part that's probably hardest to wrap your head around at first is the fact that you call selectAll on elements that don't yet exist. 最初可能最难解决的部分是你在尚不存在的元素上调用selectAll这一事实。 This is part of the "data bind." 这是“数据绑定”的一部分。 You're binding the data to a selection and D3 will create, remove, and update the elements as the data changes. 您将数据绑定到选择,D3将在数据更改时创建,删除和更新元素。 When you call enter, D3 creates elements for each member of the data that don't already have them, using the element called with append and the attributes chained on after. 当您调用enter时,D3使用带有append的元素和之后链接的属性为每个尚未拥有它们的数据成员创建元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM