liveBook · Manning

Data()

As explained in D3.js in Action, Third Edition

data() is a D3 selection method that associates an array of data values with the selected document elements.

data() associates each datum—a single data value or row—with a selected DOM element. Chained between selectAll() and join(), it tells D3 how many elements the visualization needs. section 3.3

Build the standard binding pattern progressively:

  • Select the element type that will represent each datum, often through an initially empty selection such as selectAll("rect"). section 3.3
  • Pass the dataset to data(data), allowing D3 to match data values with the selected elements. section 3.3
  • Finish with join("rect") to append one SVG rectangle for each data row; the bar-chart example produces 33 rectangles. section 3.3 section 3.6
selection
  .selectAll("selector")
  .data(myData)
  .join("element to add");

Use the chained selection–data–join pattern as the basic implementation template. section 3.3

During updates, pass a key function as data()’s second argument, such as data(updatedData, d => d.uid). Stable keys keep existing elements associated with the same data item instead of matching by position. section 7.4.2

innerChart
  .selectAll("circle")
  .data(updatedData, d => d.uid)
  .join("circle")
    ...

The keyed update pattern preserves the identity of circles that remain after a filtered dataset changes. section 7.4.2

A changed dataset produces enter, update, and exit selections: new elements are created, retained elements may change, and obsolete elements are removed. Each bound datum is available to attribute functions and is passed to child elements. section 7.4.2 section 3.6

How D3.js in Action, Third Edition covers it

How deep it goes
Explains chaining, generated elements, keyed updates, and enter/update/exit behavior without descending into D3 internals.
Examples
Uses a bar chart with 33 SVG rectangles and a filtered cetacean scatterplot to demonstrate initial binding and stable updates.
What it assumes
Assumes basic D3 selections and DOM elements while teaching the binding workflow from an empty selection.
What you can do after
Apply it via D3 to create, update, and remove visualization elements from changing datasets.
How it connects
Connects data binding with selectAll(), join(), DOM elements, key functions, and enter, update, and exit selections.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.