Livecoding: A choropleth in React.js
In this live coding session, and textual follow up, we'll go over how to use React.js to manipulate data on a map, taking medium income per US counties as our example.
Join the DZone community and get the full member experience.
Join For Free
i just spent 3 hours normalizing datasets. then i wrote a script that did it in less than 5 seconds. i am not a smart man.
did you know there were 32 states with a washington county in the us? and there are 24 jackson counties? 16 wayne counties… 12 marshalls…
county names are only unique per-state, not per-all-of-the-country. now you know. and now i know, too!
fixing that problem let me turn this picture from my live coding session:
into this picture:
the latter has less gray and more blue. that’s good. it means there are fewer counties that didn’t match our dataset. some remain. i don’t know how to fix those.
you’re looking at a choropleth map of median household incomes in the united states that i built with react and d3v4.
buffalo county in south dakota is the poorest county in the us with a median household income of $21,658. city of falls church county in virginia is the richest with $125,635. the richest part of the country is about 6x richer than the poorest.
these are medians we’re talking about, not maximums. in both cases, 90% of households fall within a few thousand dollars of the median.
more about that later when we compare this median household data to that dataset of salaries in the software industry. that should be fun.
here’s how it’s built
we cribbed off of mike bostock’s choropleth example and modified it for react.
after loading our datasets – a topojson of us counties and states (geo info) and a table of median household incomes per county – we start with a
countymap
component. it draws the overall map and deals with calculating the quantize threshold scale for colors.
the component is about 50 lines, so i added comments to each method.
|
i hope that makes sense. it follows my standard react+d3js approach .
for the counties, we can use a stateless functional component that gets all relevant data through props. it looks like this:
|
with some setup and a bit of data loading, those two components create a choropleth map of median household incomes in the united states. watch the video to see how it all fits together.
Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments