简体   繁体   中英

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

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. You can do this with selectAll and enter . Read Mike Bostock's tutorial on selections for the details of how this works and the real magic behind the scenes. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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