d3.js Washington State Unemployment Map

Every Wednesday I participate in a hack night called "Code for Seattle" which is a brigade of the "Code for America" organization. Tonight the event was held at Socrata's office, so naturally there were quite a few Socrata employees there buzzing with ideas. I teamed up with Meridith Sloth and we produced a d3.js driven Chloropleth unemployment rate map for Washington State Counties.

Check out our sample (code)

This was my first time working with d3 and it was really cool! Using the Chloropleth example as a bit of a starting point. Most of my time was spent in vim filtering out non-Washington specific.

The data that Meridith had procured for the project had a different schema than the example. Which meant we had some mapping to do. Luckily underscore to the rescue!

  var data = {};
  d3.json("http://data.wa.gov/resource/ak95-mjh9.json", function (json){
    _.each(json, function (county) {
      data[county.county_fips_code] = county.unemployment_rate;
    });
    counties.selectAll("path")
    .attr("rate", rate)
    .attr("class", quantize);
  });

  function quantize(d) {
    return "q" + Math.min(8, ~~(data[parseInt(d.id.slice(-3))] * 9 / 12)) + "-9";
  }

The quantize function was meant to convert the unemployment percentage to a 8 based scale for the css color class. Notice the double tilde? Turns out that is a bitwise operator that is often used as a faster alternative to Math.floor(). It's only practical use is to convert Floats to Integers, but it does so with much better performance.

I dropped in require.js which has always turned out to be a fantastic idea. I managed to get this rolling pretty fast without Grunt this time around.

I spent a LONG time looking for a way to pluck two value from an object and create an object setting one value as the key and the other is a value. If you know of one hit me up on Twitter @hankyates