Choropleth Maps in Altair: US States and World Maps

Draw choropleth maps in Altair with mark_geoshape() and transform_lookup(): US states, color scales, missing values, and a world map.

An Altair choropleth map has three parts: alt.topo_feature() loads the shapes, transform_lookup() joins your values to them, and mark_geoshape() draws the filled regions. You don't need GeoPandas for state or country maps. The code here uses Altair 6.2.

Quick Example

import altair as alt
import numpy as np
import pandas as pd

# State outlines, pinned to a fixed version.
states_url = "https://cdn.jsdelivr.net/npm/[email protected]/states-10m.json"
states = alt.topo_feature(states_url, "states")

# Made-up values: rooftop solar installations per 1,000 homes.
names = """Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut,
Delaware, District of Columbia, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana,
Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan,
Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire,
New Jersey, New Mexico, New York, North Carolina, North Dakota, Ohio, Oklahoma,
Oregon, Pennsylvania, Rhode Island, South Carolina, South Dakota, Tennessee, Texas,
Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming"""
solar = pd.DataFrame({"state": [n.strip() for n in names.replace("\n", " ").split(",")]})

rng = np.random.default_rng(26)
leaders = {"Arizona": 52, "California": 61, "Hawaii": 74, "Nevada": 44,
           "New Mexico": 33, "Utah": 36, "Massachusetts": 38, "New Jersey": 35,
           "Colorado": 29, "Vermont": 27}
solar["per_1000"] = [leaders.get(s, rng.gamma(3.0, 3.5)) for s in solar["state"]]
solar["per_1000"] = solar["per_1000"].round(1)

choropleth = alt.Chart(states).mark_geoshape(stroke="white").encode(
    color=alt.Color("per_1000:Q", title="Per 1,000 homes",
                    scale=alt.Scale(scheme="yelloworangered")),
    tooltip=[alt.Tooltip("properties.name:N", title="State"),
             alt.Tooltip("per_1000:Q", title="Per 1,000 homes")],
).transform_lookup(
    lookup="properties.name",
    from_=alt.LookupData(solar, "state", ["per_1000"]),
).project("albersUsa").properties(width="container", height=360)
choropleth

Interactive Altair choropleth of made-up rooftop solar rates by US state, darkest in Hawaii, California and Arizona

The outlines come from us-atlas, a TopoJSON packaging of US Census Bureau boundaries. The solar numbers are invented for this example. "albersUsa" is the usual projection for US maps: it moves Alaska and Hawaii below the southwest, and it leaves out territories such as Puerto Rico.

How Does the Data Join Work?

The chart's data is the map file, one row per shape. transform_lookup() adds your columns to those rows:

  • lookup is the key in the map data. State names are at properties.name, and the FIPS code is at id.
  • alt.LookupData(solar, "state", ["per_1000"]) gives your DataFrame, its matching key column, and the columns to bring across.

Names have to match exactly. A state spelled differently gets no value and isn't drawn, with no error. To join on FIPS codes, use lookup="id" and keep the codes as two-character strings ("06", not 6).

Use Binned Color Scales

A smooth gradient makes it hard to read a value off a map. A threshold scale gives each range one color, with the break points you choose.

binned = choropleth.encode(
    color=alt.Color(
        "per_1000:Q", title="Per 1,000 homes",
        scale=alt.Scale(type="threshold", domain=[5, 10, 20, 40],
                        scheme="greens"),
    )
).properties(width=520, height=330)
binned

US state choropleth with five shades of green for ranges below 5, 5 to 10, 10 to 20, 20 to 40, and 40 or more

Four break points make five classes. type="quantize" splits the data range into equal-width bins, and type="quantile" puts about the same number of states in each color.

Show Increases and Decreases With a Diverging Scale

For change around zero, pick a two-ended scheme and pin its midpoint with domainMid=0.

solar["change"] = (rng.normal(2.0, 4.5, len(solar))).round(1)

diverging = alt.Chart(states).mark_geoshape(stroke="white").encode(
    color=alt.Color("change:Q", title="Change from last year",
                    scale=alt.Scale(scheme="purplegreen", domainMid=0)),
).transform_lookup(
    lookup="properties.name",
    from_=alt.LookupData(solar, "state", ["change"]),
).project("albersUsa").properties(width=520, height=330)
diverging

US state choropleth using purple for states that fell and green for states that rose, with white at zero

Without domainMid, the neutral color sits halfway between the minimum and maximum, so a small increase can look like a decrease.

Show Missing Data in Gray

States without data disappear from the map. Draw a gray layer of every shape first, then put the colored layer on top.

surveyed = solar[~solar["state"].isin(
    ["Montana", "Wyoming", "North Dakota", "South Dakota", "Idaho", "Alaska"])]

background = alt.Chart(states).mark_geoshape(fill="#d9d9d9", stroke="white")
foreground = alt.Chart(states).mark_geoshape(stroke="white").encode(
    color=alt.Color("per_1000:Q", title="Per 1,000 homes",
                    scale=alt.Scale(scheme="blues")),
).transform_lookup(
    lookup="properties.name",
    from_=alt.LookupData(surveyed, "state", ["per_1000"]),
).transform_filter("isValid(datum.per_1000)")

with_missing = alt.layer(background, foreground).project("albersUsa").properties(
    width=520, height=330,
    title=alt.Title("Rooftop solar", subtitle="Gray: not surveyed"),
)
with_missing

US choropleth in blue with Alaska, Idaho, Montana, Wyoming, North Dakota and South Dakota shown in gray as not surveyed

project() goes on the layered chart so both layers use the same projection.

Make a World Map

The world-atlas package holds country outlines from Natural Earth, which is public domain. Its names are abbreviated in places ("Dem. Rep. Congo", "Dominican Rep.") and the United States is "United States of America".

world = alt.topo_feature(
    "https://cdn.jsdelivr.net/npm/[email protected]/countries-110m.json",
    "countries")

# Made-up values: customers by country for an online shop.
customers = pd.DataFrame({
    "country": ["United States of America", "Canada", "Mexico", "Brazil", "Argentina",
                "United Kingdom", "France", "Germany", "Spain", "Sweden",
                "Nigeria", "South Africa", "India", "Japan", "Australia"],
    "customers": [8200, 2100, 950, 1700, 420, 3100, 1900, 2600, 880, 640,
                  310, 520, 2900, 1500, 1250],
})

land = alt.Chart(world).mark_geoshape(
    fill="#e5e5e5", stroke="white"
).transform_filter("datum.properties.name != 'Antarctica'")

shaded = land.mark_geoshape(stroke="white").encode(
    color=alt.Color("customers:Q", title="Customers",
                    scale=alt.Scale(type="log", scheme="viridis", reverse=True)),
    tooltip=[alt.Tooltip("properties.name:N", title="Country"),
             alt.Tooltip("customers:Q", title="Customers", format=",")],
).transform_lookup(
    lookup="properties.name",
    from_=alt.LookupData(customers, "country", ["customers"]),
).transform_filter("isValid(datum.customers)")

world_map = alt.layer(land, shaded).project("equalEarth").properties(
    width="container", height=330)
world_map

Interactive Altair world map shading 15 countries by made-up customer counts on a log scale, with the United States highest and other countries gray

"equalEarth" keeps country areas in proportion, which suits shaded maps better than Mercator. The log scale stops the largest market from washing out the smaller ones.

Practical Tips

  • Map rates or per-person values. Raw counts mostly show where people live.
  • The map files load from the web when the chart renders, so viewing and saving both need a connection. To work offline, download the file and pass its contents with alt.InlineData(values=..., format=alt.DataFormat(type="topojson", feature="states")).
  • For US counties, use counties-10m.json with the feature "counties" and join five-character FIPS codes to id.
  • With your own shapefiles, pass a GeoPandas GeoDataFrame in longitude and latitude (EPSG:4326) straight to alt.Chart().
  • Large states dominate the eye. If every region matters equally, a sorted bar chart may be clearer.

Similar Topics