Upperstage
Upperstage

Reputation: 3757

How to bind data in D3 using a function

I am having trouble determining how D3 calls my "bind data function." I see my function called (with null and what appears like an index), but what are the arguments provided? How many times will D3 call this function? What are the obligations of myDataFunction?

circlesGroup.selectAll('circle').data( myDataFunction, myKeyFunction );

Upvotes: 0

Views: 291

Answers (2)

AmeliaBR
AmeliaBR

Reputation: 27544

As @Lars Kotthoff said in the comments, when you use the form .data( dataFunction, keyFunction ), your data function should return an array of data values.

But why use a function at all, and what are the parameters to it? This structure is useful if you have nested selections. Nested selections maintain a two-level hierarchy: each of the elements in the child selection is grouped according to their ancestor element in the parent selection.

When you do

parentSelection.selectAll(".childElements").data( dataFunction, keyFunction )

The data function will be called once for each element in parentSelection, and it must return an array of data to be used as for children of that parent element.

Your function will be passed the data and index of the parent object as parameters in the standard function(d,i) format. Your function then uses the parent data and/or index to determine the child data array. In the simplest situation, your parent data object is an array, and you just use function(d){return d;} to assign each element of the array to a different child.

Mike Bostock's Nested Selections tutorial gives examples of using nested selections to create a table. Nested selections are also used to create "small multiple" graphs like these donut charts: The first selection defines each pie/donut, and then the nested selection uses a data function to generate the data array for each individual slice.

Upvotes: 2

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

From the documentation:

The specified values is an array of data values, such as an array of numbers or objects, or a function that returns an array of values.

The first argument to .data() should be a data array or a function that returns a data array. It will be called once.

Upvotes: 1

Related Questions