`px.choropleth()#
We can easily imagine a scenario in which a map with point data (or a scatterplot on a map projection system) is not the most effective way to represent data. For example, when working with geospatial units that are not singular latitude and longitude points, representing an area using a polygon may yield a more insightful plot.
When working with data at the county, state, country, etc. level, polygons may be preferable to points. We call these kinds of maps choropleth maps.
We can use the px.choropleth()
function to create an outline-based choropleth map in plotly
.
Geometry Data#
First, we need to load our geometry data.
For this example, we’ll work with county-level national data.
import requests, json # import statements
r = requests.get("https://raw.githubusercontent.com/kwaldenphd/elements-of-computing/main/book/data/ch12/geojson-counties-fips.json") # get data
data = r.json() # store return
Attribute Data#
We have our geometric information loaded. Now onto the attribute data, or data values indexed by an id field.
This example uses county-level unemployment data, indexed by FIPS code as the unique id.
import pandas as pd # import statement
# load data
df = pd.read_csv("https://raw.githubusercontent.com/kwaldenphd/elements-of-computing/main/book/data/ch12/fips-unemp-16.csv",
dtype={"fips": str})
df.head() # show output
Plotting the Map#
Now we can work with the geometric information and the attribute data to generate a choropleth map. We do this using the px.choropleth()
function.
# create figure
fig = px.choropleth(df, geojson=data, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
# update figure margins
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
# show figure
fig.show()
Behold, a choropleth map showing unemployment rates for US counties. A few notes on this example:
We set the
data
GeoJSON as the geometry dataWe specify the common field to use to connect the two datasets,
fips
We base polygon color on the
unemp
field usingcolor
We set the number of colors or color range using
range_color
We select a continuous colormap using
color_continuous_scale
And we update the
unemp
field name using `labels