If you follow the data visualization community, everyone seems crazy about maps at the moment. Personally, I feel that it is in large part to the fact that Mike Bostock works with the New York Times. News and data visualizations relevant to the Times typically needs to marry up nicely with location.
So, I thought, let’s take a look at what a reusable map would look like. To start, I needed to:
- Acquire some relevant data.
- Code up a reusable map of the U.S. I decided to take it simple and only worry about States.
- Wire up a visualization composed of reusable assets: Vertical Legend, Bar Chart, and our new US State Map component.
This was surprisingly hard. I don’t want to go off on a rant here, but all of the datasets I have acquired from Government sources required tons of transformation. This dataset was no different. Dex was up to the task, but the flow that cleaned up the dataset was pretty ugly. I won’t be sharing that 🙂
Data preparation took roughly twice as long as writing a new reusable component and wiring up the visualizations and fixing bugs along the way.
Visualization #1: A Simple Usage
Here is a simple map demo. Click it to see the live content.
It’s plain, but consider that it is the result of 3 logical lines of code (spread out over 11 for readability).
In this example, we illustrate the power of reusable charts by combining three components:
- Vertical Legend – So our color bars make sense.
- US State Map – So we can easily navigate through the state data we wish to see.
- Bar Chart – So we can see the numerical data corresponding to the mouseover state.
With reusable components, this fairly powerful visualization was pretty straightforward to produce; amazingly so!
Here I will cover only the important parts of the code.
First we set up the SVG. Nothing new here.
Next, we instantiate a map.
We then configure our chart’s labels and a raw array of state data. In this example the data is embedded within the visualization; however, this data can easily be externalized into separate data files or through some sort of service layer. For now I am keeping it simple.
I then transform this data into a more convenient structure where state name is used as an index to get at the row of data.
We now instantiate a bar chart:
Now I tell the bar chart to pay attention to the mouseover events coming from the map. One of the fields within this event is the “state” field. This represents the U.S. state that the mouse is currently over. If we find the state in our list of data then we remove the old bar chart, fetch the relevant data row from our dataset and update the bar chart with this data. We then render the bar chart.
We set up our legend. It’s pretty much the same as the labels minus the first column of data (State).
Lastly, we render it all.
And that’s it, for a relatively involved D3 visualization; made much simpler through the creation of reusable components.
Thanks for listening…