D3.js Data Update Pattern

Craig Oda
CodeCakes
Published in
1 min readOct 31, 2018

US Rainfall Part 5— Updating data

The Code Cakes Project

Previous Lessons

  1. Remove Characters from Beginning of JavaScript String
  2. Divide Large Data Set into Smaller Data Sets
  3. Handling Radio Buttons in D3.js
  4. Set Up SVG Viewport with D3.js

Steps

The basic update pattern is:

  1. select
  2. data
  3. exit
  4. update
  5. enter
  6. append

In a previous lesson, you changed the data set based on radio button input. Plot the data to the screen as circles.

Select

assign the result of the select state

const circles = svg.selectAll('circle')

Data

chain the data command to the circles. Bind the data to the circles

.data(dataset);

Exit

return all the circles that are on the screen, but not in the data set.

circles.exit().remove();

Update

Update the circles that are on the screen with the new data set.

circles.attr('cy', d => height - d.rainfall * 10);

Enter

Get the circles that are in the data set, but not on the screen

circles.enter()

Append

Draw the circles that are in the data set, but not on the screen.

circles.enter()
.append('circle')
.attr('cy', d => height - d.rainfall * 10)
.attr('cx', (d, i) => i * 80)
.attr('r', 5);

Next Lesson

D3.js Scales for x-Axis

Code Cakes Project Information

--

--

Craig Oda
CodeCakes

open source advocate, writer, Flutter developer, father, husband, fly fisherman, surfer