DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Livecoding: A choropleth in React.js

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.

Swizec Teller user avatar by
Swizec Teller
·
Apr. 12, 17 · Web Dev Zone · Tutorial
Like (0)
Save
Tweet
4.14K Views

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:

image title


into this picture:

image title


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.

class countymap extends component {
    // setup default d3 objects
    // projection - defines our geo projection, how the map looks
    // geopath - calculates d attribute of <path> so it looks like a map
    // quantize - threshold scale with 9 buckets
    constructor(props) {
        super(props);

        this.projection = d3.geoalbersusa()
                            .scale(1280);
        this.geopath = d3.geopath()
                         .projection(this.projection);
        this.quantize = d3.scalequantize()
                          .range(d3.range(9));

        this.updated3(props);
    }

    // update d3 objects when props update
    componentwillreceiveprops(newprops) {
        this.updated3(newprops);
    }

    // re-center the geo projection
    // update domain of quantize scale
    updated3(props) {
        this.projection.translate([props.width / 2, props.height / 2]);

        if (props.medianincomes) {
            this.quantize.domain([10000, 75000]);
        }
    }

    // if no data, do nothing (we might mount before data loads into props)
    render() {
        if (!this.props.ustopojson) {
            return null;
        }else{
            // translate topojson data into geojson data for drawing
            // prepare a mesh for states and a list of features for counties
            const us = this.props.ustopojson,
                  statesmesh = topojson.mesh(us, us.objects.states, (a, b) => a !== b),
                  counties = topojson.feature(us, us.objects.counties).features;

            // loop through counties and draw <county> components
            // add a single <path> for state borders
            return (
                <g>
                    {counties.map((feature) => <county geopath={this.geopath}
                        feature={feature}
                        key={feature.id}
                        quantize={this.quantize}
                        data={_.find(this.props.medianincomes, {countyid: feature.id})} />)}

                     <path d={this.geopath(statesmesh)} style={{fill: 'none',
                             stroke: '#fff',
                             strokelinejoin: 'round'}} />
                </g>
            );
        }
    }
}

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:

// combine array of colors and quantize scale to pick fill colo
// return a <path> element
const county = ({ data, geopath, feature, quantize }) => {
    let color = blankcolor;

    if (data) {
        color = choroplethcolors[quantize(data.medianincome)];
    }

    return (<path d={geopath(feature)} style={{fill: color}} title={feature.id} />)
};

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.

Data (computing) React (JavaScript library) Coding (social sciences) Jackson (API) Session (web analytics) Church (programming language) Database Software IT

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 3 Reasons Why You Should Centralize Developer Tools, Processes, and People
  • Python 101: Equality vs. Identity
  • Secure Proxy for HIPAA-Compliant API Analytics
  • Pub/Sub Design Pattern in .NET Distributed Cache

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo