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

Some examples of reusable charts , such as a bar chart, 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 bound to it. As far as I understand, this idiom allows you to create a chart the first time you call the chart function, but not "recreate" it, if you like, after subsequent calls. However, can anyone explain this idiom in detail? For instance:

  • Why is .selectAll("svg") instead of .select("svg") ?
  • Why isn't .empty() used to check for empty selections?
  • Is it possible to pass any array from one element to .data() ? (I assume that the purpose of this array is to simply return the input selection.)

Thanks in advance for your help.

+6
source share
1 answer

When this is called for the first time, SVG is missing, so the .enter() selection will contain the data passed to it. On subsequent calls, the choice of .enter() will be empty, and therefore nothing new is added.

Regarding specific issues:

  • .selectAll() returns an array, which can then be mapped to the array passed to .data() .
  • .empty() can be used, but it is not necessary - if the choice is empty, nothing happens. Checking .empty() will add an if and will have exactly the same effect.
  • Yes. Check out this tutorial , for example, for more information on selection.
+7
source

All Articles