Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable charts in d3: how do the create and update selections work?

Tags:

d3.js

Several of the reusable charts examples, such as the histogram, include the following:

// select the svg element, if it exists
var svg = d3.select(this).selectAll("svg").data([data]);

// append the svg element, if it doesn't exist
svg.enter().append("svg") ...

...where this is the current DOM element and data is the data that's been bound to it. As I understand it, this idiom allows a chart to be created the first time the chart function is called, but not 'recreated', if you like, following subsequent calls. However, could anyone explain this idiom in detail? For example:

  • Why is .selectAll("svg") used and not .select("svg")?
  • Why isn't .empty() used to check for an empty selection?
  • Can any single-element array be passed to .data()? (I assume the purpose of this array is simply to return the enter selection.)

Thanks in advance for any help.

like image 839
Iain Dillingham Avatar asked Dec 27 '12 23:12

Iain Dillingham


1 Answers

When this is called the first time, there's no SVG and therefore the .enter() selection will contain the data passed to it. On subsequent calls, the .enter() selection will be empty and therefore nothing new added.

Concerning the specific questions:

  • .selectAll() returns an array which can then be matched to the array passed to .data().
  • .empty() could be used, but it's not necessary -- if the selection is empty, nothing happens. Checking .empty() would add an if statement and have exactly the same effect.
  • Yes. Have a look this tutorial for example for some more detail on selections.
like image 137
Lars Kotthoff Avatar answered Nov 15 '22 10:11

Lars Kotthoff