I’ve been trying to learn D3.js via Mike Bostock’s excellent “Let’s make a bar chart” tutorial series. This post is my attempt to extend that example to handle data updates.
Starting point
Part 3 of the tutorial ends with a bar chart that shows the relative frequency of letters used in the English language.
The creation of each bar per datum is handled by this code:
This says we’re dealing with chart elements of the CSS class .bar
for each datum. The .enter()
call tells D3 we want to perform the operations that follow for any new data (data that has entered source). We can also use .exit()
for data that is no longer in the source. If we want to handle updated data we can add properties directly (outside of enter()
/ exit()
).
Adjusting the bars for new data
To specify updates I had to change the data join so D3 knows how to differentiate added, removed and updated data. In this case we will use the name
property, which is a letter from A
to Z
.
Next we’ll modify the code to specify how to handle updated and removed data, instead of just what to do on enter()
for new data.
Updating the axes
This was enough to update the chart, but the y-axis would draw the new axis over the top of the previous axis, so both values would show. This answer on StackOverflow suggested removing the axis and redrawing it each time, which worked well.
Basic transition
The next thing I wanted to try was animating changes to existing data. This turned out to be trivial thanks to D3’s transition()
method, which I just dumped prior to the code we used to update each bar.
And that’s it!
End result
Here’s an example of the update in action. Use the radio buttons to alternate between the chart showing frequencies of letters in English and the frequencies of letters used in the source for this post.