Tile Choropleth Maps in Python
How to make tile choropleth maps in Python with Plotly.
Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.
A Choropleth Map is a map composed of colored polygons. It is used to represent spatial variations of a quantity. This page documents how to build tile-map choropleth maps, but you can also build outline choropleth maps.
Below we show how to create Choropleth Maps using either Plotly Express' px.choropleth_map function or the lower-level go.Choroplethmap graph object.
Introduction: main parameters for choropleth tile maps¶
Making choropleth maps requires two main types of input:
- GeoJSON-formatted geometry information where each feature has either an
idfield or some identifying value inproperties. - A list of values indexed by feature identifier.
The GeoJSON data is passed to the geojson argument, and the data is passed into the color argument of px.choropleth_map (z if using graph_objects), in the same order as the IDs are passed into the location argument.
Note the geojson attribute can also be the URL to a GeoJSON file, which can speed up map rendering in certain cases.
GeoJSON with feature.id¶
Here we load a GeoJSON file containing the geometry information for US counties, where feature.id is a FIPS code.
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
counties["features"][0]
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
df.head()
Choropleth map using plotly.express and carto base map¶
Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on a variety of types of data and produces easy-to-style figures.
With px.choropleth_map, each row of the DataFrame is represented as a region of the choropleth.
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth_map(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
map_style="carto-positron",
zoom=3, center = {"lat": 37.0902, "lon": -95.7129},
opacity=0.5,
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()