Repository navigation
使用D3.js进行滚动叙事 #107
chengjun
started this conversation in
Show and tell
Replies: 1 comment
Another D3.js scrolling stories — TitanicCLICK to see demo The Rhythm of Food Why Titanic data? As Udacity Reviewer I ‘ve seen 100’s of examples of Titanic visualisations (some better than others) and I’ve also had a crack at the Kaggle challenge myself so it’s data I know well. I also had the luck to find a working example of a scroller by the brilliant Jim Vallandingham. My challenge was to adapt this to my own resources and it’s been great fun. I’ve published the code on Github with more detailed comments in the code and you can see a working example here. I’ve recently found Scrollama which would be another good starting point. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

Uh oh!
There was an error while loading. Please reload this page.
How I Created an Interactive, Scrolling Visualisation with D3.js, and how you can too
College Majors separated by category
Motivation
The web is littered with stunning examples of scrolling and interactive visualisations, often built using D3. If you’ve ever read such feature pieces from Bloomberg or the New York Times, I’m sure you know what I’m talking about. Some of my favourite examples of this form are:
Shirley Wu’s exemplary visualisation of very line in Hamilton, built with D3 and React. In fact, all of her work is excellent.
The New York Time’s piece of how the economy has been reshaped by the recession, told in 255 different charts.
This absolutely mind-boggling piece, visualising the inner mechanics of Machine Learning, created by the folks over at R2D3.
This quirky visualisation, breaking down the amount of water which we consume on a daily basis
Another article from the NYTimes, illustrating the treacherous climb up El Capitan’s dawn wall
And so many more.
Seriously, every single one of these projects is worth checking out and learning from. They are amazing.
There’s something satisfying about the way in which the visual elements comport themselves after each scroll event, bending to your control. Often times, I have a huge smile on my face as I scroll up and down the page, watching all the shapes and colours fly around. It’s a sensation reminiscent of discovering the secrets held by the data on your own, which is what I believe makes these presentations so convincing. It also provides a much more commanding narrative flow, which would otherwise be lacking in more static pieces. Browsing through these articles, it may appear that such visualisations would be extremely complicated to produce on your own, and you may assume they are best left to the editors and writers of top-shelf publications. But I’m here to help dispel this notion: Anyone can make one, including you!
After reading through a bunch of online resources (I will leave a list of these at the end of the article), I decided to take a stab at creating one myself. As I’ve mentioned before, the best way of learning a new tool, technique, skill or ability is to put it to use, before you even know if you’re capable of doing that thing. And so that is exactly what I did over the course of a week.
(This article will assume you have some basic familiarity with D3.js and how it works)
Project Description
After browsing through a series of datasets, I settled on one which I found hosted on Kaggle, which originally came from the analytics blog Fivethirtyeight (if you’re looking for cool datasets, check out google’s dataset search tool). It was a (slightly outdated) dataset about college majors around the United States. It had information on the number enrolled in each college major, as well as the median, 75th percentile and 25th percentile salaries from those students. Interestingly, it also provided information on the male/female representation for each major, which I thought would be a good point of focus for the piece.
With the dataset decided, I started exploring the data using Python and Pandas in Jupyter notebooks, looking for any interesting trends or points I would want to emphasise in a visualisation. I also made rough, crude approximations of the graphs I would want to show in the final product.
A couple of the sketches I hastily threw together, just to roughly diagram the narrative flow I hoped to achieve
My general conception of the visualisation was that the college majors would each be represented by a bubble. The bubbles would then change form and colour based on the type of data I was trying to highlight (ie gender discrepancies, median salary, category grouping etc.). When the bubbles would be grouped in by specific attributes, I wanted to achieve this through a D3 force simulation, so that the bubbles would appear to be gravitating towards an unseen force.
A preview of the gender distribution vs median salary graph I made using matplotlib. I was exploring the data to see whether there were interesting trends to highlight.
After some exploration, I knew that I wanted to focus on the impact that gender distribution within a major has on the median salary of its graduates. I would strongly suggest that you take a deep dive into your data before starting any of the visualisation process, because you want to have some semblance of the interactions you have in mind before actually sitting down to code the final product.
If you want a really quick way of observing relationships between variables, the python visualisation package seaborn has a ‘pairplot()’ method to help you do just this, which creates a matrix of scatterplots between all of the variables in the dataframe passed to it.
An example pairplot created from a subset of the data
Now we have a solid idea of the things we want to include, we are ready to start creating.
Handling the Scroll Events
This is (obviously) the most important part of every scroller you build. But conveniently, it’s also the most reusable part, meaning that after you build it once, you should be good to go.
In fact, I’ve created a template version of the scroller functionality, which you can find right here. (credits again to Jim Vallandingham, as much of the code used was sourced from his original article. In fact, he wrote a similar article on creating a scroller, with an emphasis on the scrolling mechanics, so you should read that first. In this article, I will focus on the elements which I found confusing, and put a greater emphasis on the part of actually creating the visualisation).
HTML and CSS Outline
The entire visualisation should be contained within a single HTML page. Within the page, there is a div which contains all the elements, and within that div, there are two separate divs for the text and the visualisation.
Within the ‘sections’ div are a bunch of section elements, each with the class ‘step’. Each one of these sections should contain a distinct section of text, and correspond to one phase or part of the visualisation. It is when the user moves between sections that the visualisation will be updated,
You can size and position these elements as you wish, so long as you keep the #vis element fixed on the page (using display: fixed), so it doesn’t move as the user scrolls. You can also tweak the height of each .step element based on how much text you want to include per section.
Scroll Events
Here is the code which handles the scroll events. I’ve added comments to clarify certain parts.
All of the above code is saved in a separate script file. We then create a main script file, which is responsible for updating the visualisation every time the viewer changes sections.
General Advice for Building a Scroller
With the generic components of the scroller sorted out, what you do from here is going to vary greatly based on the type of visualisation you are hoping to construct. Nonetheless, I can hopefully offer some broad brush advice that may come in handy, and which I wish I had been aware of sooner in the process.
Draw all the Elements at the Start
The essential idea is that all the elements that you need for the visualisation should be created when the page loads. I created a function called drawInitial(), and invoked it once the data was loaded in. This involves creating all the scales, axes, shapes, for simulations and other elements which you will need in the visualisation.
Once they are all created, you can simply set their opacity attribute to 0 to ensure that they don’t show up until required by the visualisation. Make sure each set of features (ie a set of axes for a particular chart, or a detail callout) has associated class or ID names, so that you can reference those specific features when required.
I found it useful to create a cleaning function, which would be invoked at each step. I would pass in the chart type which I was trying to create, and the function would remove (or hide, rather) all the elements which were extraneous to that chart, thus saving me from having to write a lot of duplicated code. This is what part of the function looks like:
Dealing with The Force
As I mentioned, I would be using force simulations to group the circle elements in several of the phases. The key thing to remember is to ‘reheat’ the force simulation every time you bring it back into use. Force simulations in D3 have an alpha value, which is a cooling parameter that gradually decrements over time, and reduce how much the force impact the nodes. You should reset the alpha back to a certain value every time you restart the force, to make sure it has enough ‘energy’ to get to the desired state. You can also tweak the alpha decay rate to affect how quickly the simulation settles down to an equilibrium state.
Always Use Transitions
This part is key: Always use transitions when changing the state of the visualisation, even if that change is something you want to be instantaneous. By utilising D3’s transition feature (even if the duration is 0), you allow the changes to be interrupted. This means that if the user is scrolling through the sections quickly, one transition can be overridden by a subsequent one, avoiding the case where you are left with an awkward, invalid state.
You Raise Me Up
SVG elements are ordered based on when they were appended to the parent element. Think of it like throwing paint on a canvas: the last layer of paint is the one that’s visible on top. You could reorder elements by removing them from their parent element, and then appending them again to the very end. Alternatively, you could make use of D3’s .raise() and .lower() methods, which conveniently do this exact process for you when given a selection of elements.
Building a Consistent Colour Palette
Colours are an indispensable component of good data visualisation. For parts of my project, I was trying to encode with colour 16 different categories of college majors. This led to an elaborate process for selecting colours, as I wanted to avoid any two hues which were too similar and thus easily confused.
I highly recommend using Color Hunt in building your palettes. It’s a website where other creatives have constructed and shared their own palettes, and it allows you to easily copy the hex-codes of the hues which you want, and to save your own palettes as well for future use.
Hopefully, this has demystified at least part of the process of making a scrolling visualisation. It’s honestly much easier than it looks, and so definitely go find an interesting dataset and try it out for yourself!
Resources Consulted
All reactions