Drawing US Map in D3 (Chloropleth)

The choropleth is easily the hardest project, right up until it isn’t, and then it’s as easy as the bar graph. Crossing that gap is the hard part. The steps are basically the same on both projects. You need to fetch the data (you can do that already), you need to process it so that you’ve got a data set to iterate over (like the GDP data), and you need to draw it (just a bar, almost), color it (just like the heatmap with a color scale), and add the tooltips (just like every other project).

The hard part is getting started since there is nothing in the practice about mapping and it’s not obvious from anything what format the data is. The education data is just plain, self-explanatory JSON. It’s fips field is the US Census FIPS ID for the county and is the same as the id field in the counties data. The county data is the geography information in topoJSON format (the type: "Topology" field is the hint) which along with geoJSON is one of the map formats that D3 handles best. This data is JSON, with three different types of geography objects: counties (array of county boundaries), states, and nation. These three will be used to draw the counties, states, and nation boundaries. The catch is that topoJSON is a condensed format, and has to be converted to geoJSON before drawing. You can use the library topojson-client to do the conversion.

Once you have the geoJSON, you can draw the counties. The geoJSON data looks similar to topoJSON, but it has been converted into coordinates (either latitude/longitude or projected latitude/longitude; this is the latter). This data is in the field features, which is an array of objects containing information about the feature in the properties field and arrays of coordinates in the geometry field, something like

{
  ...
  'features': [
    {
      'type': 'Feature',
      'properties': {
        'id': 01127,
        'name': 'Walker County',
        ...
      },
      'geometry': {
        ...
      }
    },
    ...
  ]
}

So to draw the counties, all you have to know is the projection to tell D3 (it’s Albers USA), and then pass the feature to D3’s geoPath function for drawing (usually you do this by iterating over the features array, just like drawing rects by iterating over the GDP data array). Once you can draw counties, you can link the county and education data via the id/fips fields and do the the rest of the stuff that’s the same on all the projects.

To summarize what you’ll need to know:

  • the topojson-client function to convert an array of objects (in topoData.objects.counties, or whatever you name the fetched data) to geoJSON
  • how to set the D3 projection to Albers USA
  • how to use d3.geoPath() to draw a path with a set of coordinates (a feature)
  • how to iterate over your generated features in some variable like geoData.features like you did with the GDP data from the bar graph
  • how to do the rest of the stuff all these projects require
6 Likes