liveBook · Manning

Data binding

As explained in D3.js in Action, Third Edition

Data binding is a pattern that associates data values with document elements so the elements can be generated or updated from those values.

Data binding associates each datum with a DOM element, letting a visualization generate its marks from data. In D3, a bar-chart rectangle can represent one technology and its count; the same pattern works for SVG and ordinary HTML elements. section 3.0 section 3.3 section 5.3

Start with a container selection, make an empty selection for the element type, supply the dataset, and join the elements. The empty selection is intentional: it gives D3 a place to determine how many elements the data requires. section 3.3

Create one rectangle per row

To make a bar chart, select the SVG container, select all rect elements, bind the dataset, and join rect. A dataset with 33 rows produces 33 rectangles in the DOM. Then use each bound datum in inline functions to set visual attributes. section 3.3 section 3.6

Figure 3.17 The data-binding process
figure

Follow the sequence from container selection to empty selection, dataset, and generated elements. section 3.3

Bound data is available to an element and passed to its children. Bind arc objects to SVG groups when both a path and a text label need the same values, such as angles, percentages, and centroids. section 3.6 section 5.1.4

Binding also supports updates. After filtering a scatterplot, bind the revised dataset again. A key function such as d => d.uid preserves the connection between surviving circles and their data; join can then distinguish entering, updating, and exiting elements. section 7.4.2 section 7.4.2

Use the same pattern beyond chart marks

Bind format records to list items to build a color legend, or bind filter records to buttons to create an interface. D3 can generate and manipulate any DOM element, not only SVG shapes. section 5.3 section 7.2

How D3.js in Action, Third Edition covers it

How deep it goes
Explains selectAll(), data(), and join(), then develops keyed enter, update, and exit behavior for filtered views.
Examples
Uses bar-chart rectangles, donut arcs with percentage labels, an HTML color legend, histogram bins, and filtered scatterplot circles.
What it assumes
Assumes familiarity with CSS for legend layout while introducing D3 selection-based DOM binding incrementally.
What you can do after
Build it from scratch with D3 to create, update, and preserve data-linked DOM elements during visualization changes.
How it connects
Connects DOM selections, SVG, scales, arc generators, transitions, key functions, and frontend frameworks.

Also explained in

Compare how 5 books explain data binding →

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.