Michael Bostock’s D3 is a brilliantly powerful visualization framework. It can be used to generate beautiful and diverse visualizations, but most of them would be impossible without data backing them up. So how can you get data from Socrata data sites quickly and easily into D3?
Fortunately this is extremely easy with D3’s
d3.csv function and SODA’s built in CSV output type.
In this sample, we’ll walk you through the creation of the simple stacked column chart below. If you’d like to follow along at home, you can fork this jsFiddle sample project.
This example pulls data live from this Chicago Transit Authority ridership dataset via the SODA API.
To start, we’ll need to initialize some of our margins and scales for D3. This is mostly just boilerplate:
Next we’ll create the SVG container that we’ll add our chart components to:
Then we’ll pull in our data using the SODA CSV output type and D3’s
d3.csv function. We don’t need the
total column that the dataset uses, so we’ll use the
$select parameter to filter down to the four columns we really care about. We’ll also use the
$where parameter to only get ridership after 1999, and the
$$app-token parameter to pass our application token. In this case we’ve “redacted” out the application token - you should register and supply your own:
d3.csv takes a function as a parameter that is called when it retrieves your CSV data. That’s where we’ll handle our actual input. The rest of this example is from within that function body.
First we’ll make sure that D3 has properly interpreted our numbers as actual numbers. CSV doesn’t convey typing very well.
Next we’ll associate our data with our color bands:
We want our columns sorted by year, so let’s make sure that’s the case:
Set up our axes:
Now we actually generate rectangles for all of our data values:
Finally, we add a legend:
That’s it! Got a great example of your own? Please contribute to our community-maintained documentation.