Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 44 ยท Maps and Geo

Choropleth and World Maps

Load TopoJSON with topojson-client, draw a world map with d3.geoPath, join data to countries, color a choropleth with scales, add a legend and tooltips.

A choropleth colors regions (countries, states, counties) by a value. To build one you need three ingredients: the shapes, the values keyed by the same identifier, and a color scale. This lesson uses the compact world-atlas data set, a TopoJSON file hosted on a CDN, and shows how to join your numbers to it. You should already know projections and d3.geoPath from Geographic Projections and Paths.

TopoJSON in short

GeoJSON repeats a shared border twice, once per neighbour. TopoJSON stores each border once as an "arc" and lets shapes refer to arcs, so files are often 80% smaller. The browser needs the small topojson-client library to convert it back into GeoJSON:

HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/topojson-client.min.js"></script>
JavaScript
const world = await d3.json("https://cdn.jsdelivr.net/npm/[email protected]/countries-110m.json");
const countries = topojson.feature(world, world.objects.countries); // FeatureCollection
const borders   = topojson.mesh(world, world.objects.countries, (a, b) => a !== b); // internal borders only

topojson.feature() returns the shapes as GeoJSON features (each with id and properties.name in this file). topojson.mesh() returns one line geometry for all borders; drawing it once avoids doubled strokes and is much faster than stroking every country. The 110m file is the coarse resolution (about 100 KB) suitable for world maps; 50m is more detailed.

A first world map

A world map from TopoJSON

If the network is blocked the map stays empty; the code always waits for d3.json. Hover a country to see its name in the native tooltip.

Joining data and coloring

Real choropleths merge a data table with the shapes. You need a shared key: usually a country name, an ISO code or a numeric id. Build a Map from the table, then look up each feature:

JavaScript
const values = new Map(rows.map(r => [r.name, +r.value]));
fill: d => values.has(d.properties.name) ? color(values.get(d.properties.name)) : "#eee"

Always handle missing values separately (a neutral grey) so "no data" is not confused with "low value". Names in different data sets rarely match exactly ("United States of America" vs "USA"), so print the unmatched keys while developing.

Color scales for choropleths:

  • d3.scaleSequential(d3.interpolateBlues).domain([0, max]) for a continuous ramp.
  • d3.scaleQuantize(domain, colors) for equal-width classes; d3.scaleQuantile(values, colors) for equal-count classes; d3.scaleThreshold for hand-picked break points.
  • Skewed data (population, area) usually needs a log scale: d3.scaleSequentialLog(d3.interpolateYlGnBu).domain([min, max]), or classes.

Use a sequential palette for amounts, a diverging palette (d3.interpolateRdBu) when there is a meaningful midpoint, and never a rainbow.

Choropleth of country area, with legend

Because the numbers come from d3.geoArea, they are real geometric areas of the coarse shapes (small deviations from official figures are expected). The same recipe works for any measurement: replace the area map with your own Map keyed by d.id or d.properties.name.

The legend is built from the scale itself: color.range() lists the colors and invertExtent(c) returns the data interval each color covers (undefined at the open ends of a threshold scale). This is a handy trick for any quantize or threshold scale. Here d3.scaleThreshold uses hand-picked breaks because country sizes are very skewed.

Points on maps: symbol maps and bubbles

A different style, the proportional symbol map, draws a circle at each location with an area proportional to the value. Use path.centroid(feature) for countries, or projection([lon, lat]) for cities, and a square-root radius scale so that area, not radius, grows with the value:

JavaScript
const r = d3.scaleSqrt([0, max], [0, 30]);
svg.selectAll("circle").data(places).join("circle")
  .attr("transform", d => `translate(${projection([d.lon, d.lat])})`)
  .attr("r", d => r(d.value));

Sort the data so large circles are drawn first and small ones remain visible on top.

flowchart TD
  A["TopoJSON file"] --> B["topojson.feature: GeoJSON features"]
  C["Table of values"] --> D["Map keyed by id or name"]
  B --> E["fill = colorScale(map.get(id))"]
  D --> E
  E --> F["SVG paths + legend"]

A choropleth joins shapes and values through a shared key.

Common mistakes

  • Joining on names that differ between data sets; always check for missing matches.
  • Treating missing values as zero. Give them a distinct color and legend entry.
  • Using raw counts (population) rather than rates (per capita) so big regions always look "worse".
  • Stroking each country separately with a thick line, which doubles borders. Use topojson.mesh for borders.
  • Forgetting that TopoJSON ids can be strings with leading zeros (such as "004") while your data has numbers; normalise both sides.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does topojson.feature(topology, object) return?

    It converts the shared-arc TopoJSON object back into a GeoJSON FeatureCollection or Feature.
  2. 2. Why draw borders with topojson.mesh instead of stroking every country?

    mesh returns a single geometry of unique arcs, ideal for border lines.
  3. 3. Which scale class puts values into a fixed number of equal-width color buckets?

    scaleQuantize splits a continuous domain into equal intervals mapped to the range colors.
  4. 4. Why use d3.scaleSqrt for the radius of proportional symbols?

    Area is proportional to r squared; a sqrt scale makes area proportional to the value.

Summary

  • Load TopoJSON with topojson-client; feature gives shapes and mesh gives borders.
  • Join data and shapes through a shared key held in a Map; show missing data distinctly.
  • Color with sequential, quantize, quantile or threshold scales and build the legend from the scale.
  • Use equal-area projections and rates rather than raw counts when comparing regions.

Next: Zoomable and Interactive Maps