px.choropleth_mapbox()

px.choropleth_mapbox()#

We can also create tile-map choropleth maps using the px.choropleth_mapbox() function. Tile-map choropleth maps require the same two main types of input to generate a map:

  • Geometry information: can be supplied using a GeoJSON file in which each feature (polygon) has an id field that can be used to connect attribute data;

    • plotly includes built-in geometries for US states and world countries

  • Attribute data, or a list of values indexed by feature identifiers (an id reflected in the geometry information)

We’ll use the same county unemployment data from the previous choropleth map section. With px.choropleth_mapbox(), each row of the dataframe is represented by a polygon. A sample choropleth map of the county unemployment data, using the base layer carto-positron which does not require an access token.

import requests, json, pandas as pd, plotly.express as px # import statements
r = requests.get("https://raw.githubusercontent.com/kwaldenphd/elements-of-computing/book/data/ch12/geojson-counties-fips.json") # get data
counties = r.json() # store return
# load data
df = pd.read_csv("https://raw.githubusercontent.com/kwaldenphd/elements-of-computing/book/data/ch12/fips-unemp-16.csv",
                   dtype={"fips": str})

# df.head() # show output
# create figure
fig = px.choropleth_mapbox(df, geojson=counties, locations='fips', color='unemp',
                           color_continuous_scale="Viridis",
                           range_color=(0, 12),
                           mapbox_style="carto-positron",
                           zoom=3, center = {"lat": 37.0902, "lon": -95.7129},
                           opacity=0.5,
                           labels={'unemp':'unemployment rate'}
                          )

# update figure layout
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

# show figure
fig.show()
Output hidden; open in https://colab.research.google.com to view.

And again, we have a choropleth map showing unemployment rates for US counties. A few notes on this example:

  • In this example, we set the counties GeoJSON as the geometric data.

  • We specify the common field to use to connect the two datasets, fips.

  • We base polygon color on the unemp field using color.

  • 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.