- Part 1: Let’s Make a Pie Chart with D3.js
- Part 2: Let’s Update a Pie Chart in Realtime with D3.js
- Part 3: Smooth Pie Chart Transitions with D3.js (this post)
A few days ago we made a pie chart that updates in real time, but it has one issue: The update is jumpy. Let’s fix that.
I’ll admit, unlike the other tutorials where I was able to figure out most of this on my own, I had to mine other examples to figure this out. I primarily followed Mike Bostock’s Pie Chart Update, II, but his commented Arc Tween example was extremely helpful in understanding what d3.interpolate is doing.
What to do
Note: We’re starting with code from my previous Pie Chart Update tutorial.
First we need to store the beginning angle for each arc. You’ll recall that I’m using two separate arcs, one for the main chart and one for the labels. For about 10 minutes I was trying to figure out why the first update was jumpy but all subsequent ones were smooth. It turns out that we need to store the initial angles for each set of arcs:
Next we need to write two arcTween functions to transition between the two. I followed Mike Bostock’s example for the first one, then adapted it to the label arc, too:
Last we need to include these arcTween()
functions into the change()
function we wrote before. I commented out the previous updates so you can compare them. The duration is 1/2 a second:
Here is is in action. As always, you can view source to see the fully integrated example: