This video is available to students only


We talk through a more complex example: animating our line chart when it gets new data. This is trickier than it might seem at first!


After animating bars, animating line transitions should be easy, right? Let's find out!

Does this example look familiar? This is our timeline drawing code from Module 1 with some small updates.


One of the main changes is an addNewDay() function at the bottom of the script. This exact code isn't important — what is good to know is that addNewDay() shifts our dataset one day in the future. To simulate a live timeline, addNewDay() runs every 1.5 seconds.

If you read through the addNewDay() code and were confused by the ...dataset.slice(1), syntax, the ... is using ES6 spread syntax to expand the dataset (minus the first point) in place. Read more about it in the MDN docs.

We can see our timeline updating when we load our webpage, but it looks jerky. We know how to smooth the axis transitions, let's make them nice and slow.

Great! Now let's transition the line.

What's going on here? Why is our line wriggling around instead of adding a new point at the end?

Timeline wriggling?

Remember when we talked about how path d attributes are a string of draw-to values, like a learn-coding turtle? d3 is transitioning each point to the next point at the same index. Our transition's .attr() function has no idea that we've just shifted our points down one index. It's guessing how to transition to the new d value, animating each point to the next day's y value.

Pretend you're the .attr() function - how would you transition between these two d values?

It would make the most sense to transition each point individually, interpolating from 0 50 to 0 60 instead of moving each point to the left.

Great, we understand why our line is wriggling, but how do we shift it to the left instead?

Let's start by figuring out how far we need to shift our line to the left. Before we update our line, let's grab the last two points in our dataset and find the difference between their x values.


This page is a preview of Fullstack D3 Masterclass

Please select a discussion on the left.