US Rainfall Part 5— Updating data
Previous Lessons
- Remove Characters from Beginning of JavaScript String
- Divide Large Data Set into Smaller Data Sets
- Handling Radio Buttons in D3.js
- Set Up SVG Viewport with D3.js
Steps
The basic update pattern is:
- select
- data
- exit
- update
- enter
- 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);