Selections and data binding

Understand D3 selections and data binding, and use enter, update, and exit to handle additions, updates, and removals.

🎯 Introduction

Previously, we used enter().append() to build a bar chart from scratch. Real data changes: an API might return five days of sales today, seven tomorrow, and only three the next day. How do the bars keep up? This article explains D3's core data-binding mechanism.


🧱 Selections: accessing elements

Before manipulating elements, you need to select them. D3 provides two methods:

  • d3.select('svg'): Select the first matching element.
  • d3.selectAll('rect'): Select all matching elements.
d3.select('svg'); // Select the SVG element on the page
d3.selectAll('rect'); // Select all bars

The result is a selection, which supports method chaining: select elements, then apply operations in sequence. If you have used jQuery's $(), this will feel familiar.


🧱 Two ways to pass values to attr

.attr() sets element attributes. It accepts either a constant or a function, with different results:

// A constant: every bar is 40 pixels wide
svg.selectAll('rect').attr('width', 40);

// A function: calculate each bar's position separately
svg.selectAll('rect').attr('x', (d, i) => i * 60);

D3 calls the function once per element, passing d, the bound datum, and i, its index. For [120, 200, 150], it runs three times:

Calld (datum)i (index)Calculated x = i × 60
112000
2200160
31502120

style (CSS styles) and text (text content) accept values and functions in the same way as attr.


⚡ datum versus data

Both methods bind data, but they serve different purposes:

  • .data(array): Distribute array items across a selection, one datum per element.
  • .datum(value): Bind the entire value to each selected element.
// One value per bar: 120 for the first, 200 for the second, and so on
svg.selectAll('rect').data([120, 200, 150]);

// A line is one graphic, so bind the entire array to it
svg.select('path').datum(points);

Remember: data distributes array items; datum binds a value as a whole. Use data for multiple graphics and datum for a single graphic such as a line.


🧱 enter, update, and exit: matching data to elements

When .data() runs, D3 matches data to existing elements by position by default. There are three possible outcomes.

Case 1: More data than elements. Unmatched data enters the enter selection, waiting for new elements:

Data (5):     [120] [200] [150] [80] [70]
Elements (2): [rect][rect]

First 2 match → update (update existing elements)
Last 3 have no element → enter (add 3 rects)

Case 2: More elements than data. Unmatched elements enter the exit selection, waiting to be removed:

Data (3):     [120] [200] [150]
Elements (5): [rect][rect][rect][rect][rect]

First 3 match → update (update existing elements)
Last 2 have no datum → exit (remove these 2 rects)

Case 3: Equal counts. All elements belong to update, so update them directly.

A complete data update therefore has three steps:

const rects = svg.selectAll('rect').data(data);

// 1. exit: remove unmatched elements
rects.exit().remove();

// 2. update: set attributes on existing elements
rects.attr('y', d => 300 - d).attr('height', d => d);

// 3. enter: create elements for new data
rects
    .enter()
    .append('rect')
    .attr('x', (d, i) => i * 60)
    .attr('width', 40)
    .attr('fill', '#5470c6')
    .attr('y', d => 300 - d)
    .attr('height', d => d);

Remember: remove extras, update existing elements, and add missing ones.

On the first render, no elements exist, so all data enters the enter selection. That is why enter().append() alone worked previously: it is a special case of this three-step process.

🧰 join(): combine the three steps

Writing all three steps repeatedly is verbose. In D3 v6 and later, join() is available to combine them automatically:

svg.selectAll('rect')
    .data(data)
    .join('rect') // Handle enter, update, and exit automatically
    .attr('x', (d, i) => i * 60)
    .attr('width', 40)
    .attr('fill', '#5470c6')
    .attr('y', d => 300 - d)
    .attr('height', d => d);

This is enough for everyday usage. However, understand the three underlying selections first so you can customize behaviors such as entrance animations for new elements and smooth transitions for existing ones.


🔑 Match precisely with a key

The default join matches by position, which can cause problems when items are inserted or removed.

Suppose the chart contains bars A, B, and C, and you remove B from the data. A positional join matches the first two elements and removes the last: C's bar disappears, while B's bar receives C's data. The count is correct, but element identity no longer matches the data.

Give each datum a stable identifier to match it precisely:

const data = [
    { id: 'a', value: 120 },
    { id: 'b', value: 200 },
    { id: 'c', value: 150 },
];

svg.selectAll('rect').data(data, d => d.id);

With a key, D3 knows that the bar with id equal to b should leave. Additions, updates, and removals preserve identity. Always consider specifying a key for arrays of objects.

In this comparison, each id has a fixed color: A is blue, B red, and C green. Click “Remove B”. On the left, the positional join keeps B's red bar and assigns C's data to it. On the right, the keyed join removes B correctly while C retains its color and identity:

Without a key (match by position)

Match by key


❓ Questions and answers

Q1: Why call selectAll on the first render when no elements exist?

An empty selection is fine: all data enters the enter selection and append creates the elements. The same pattern works for both initial rendering and incremental updates.

Q2: When should I use attr instead of style?

Use attr for SVG attributes such as x, y, width, height, and fill, and style for CSS properties such as opacity and cursor. When unsure about an SVG attribute, attr is usually appropriate.

Q3: Can join() customize all three selections separately?

Yes. Pass three callbacks: .join(enter => ..., update => ..., exit => ...). Start with the string form; the transitions article builds on these concepts.

Q4: What happens without a key?

It works when order stays stable. Inserting, deleting, or sorting data can cause element identities to shift: removing B may remove C's element instead.


🧪 Exercise

Create a render(data) function and verify additions, updates, and removals:

  1. Call render([120, 200, 150]) to draw three bars.
  2. In the console, call render([120, 200, 150, 80, 70]) and observe two new bars.
  3. Call render([100, 60]) and observe the extra bars disappear and the remaining heights update.
const svg = d3.select(svgRef.value);

function render(data) {
    // Write your code here (hint: use join or enter/update/exit)
}

render([120, 200, 150]);

🎉 You now understand D3's core data-binding mechanism! Next, scales will help us convert values that are too large to fit directly on screen.