How to Create an Animated Choropleth Map with Less Than 15 Lines of Code | Towards Data Science

Table of ContentsIntroduction1. Choropleth maps2. Data3. Animated choropleth USA map4. Animated choropleth world mapConclusion
Plotly Express makes it easy to create animated graphs. The official document says that “Although Plotly Express supports animation for many chart and map types, smooth inter-frame transitions are today only possible for scatter and bar.”
Even though choropleth maps are not mentioned, in this article you will find just how easy it is to create animated choropleth maps using Plotly and Python on Jupyter.
This article assumes you are already familiar with the basic operation in JupyterLab/Jupyter Notebook and you have Plotly installed.
A choropleth map is a map composed of colored polygons. Plotly Express’ px.choropleth function and the lower-level go.Choropleth graph object can create choropleth maps and you can find some examples on the official website. You can only zoom in or out of the maps.
We’re going to use the murder rate in the US. Data was originally published by the FBI, and Julia Poncela-Casasnovas modified it. You can find it here.
import plotly.express as pximport pandas as pddf = pd.read_csv('https://gist.githubusercontent.com/shinokada/f01139d3a024de375ede23cec5d52360/raw/424ac0055ed71a04e6f45badfaef73df96ad0aad/CrimeStatebyState_1960-2014.csv')df = df[(df['State']!= 'District of Columbia' )]df
The DataFrame’s columns have the following values.
df.columns# OutputIndex(['State', 'Year', 'Population', 'Violent_crime_total',       'Murder_and_nonnegligent_Manslaughter', 'Murder_per100000',       'Legacy_rape_/1', 'Revised_rape_/2', 'Robbery',   'Aggravated_assault', 'State_code'], dtype='object')
towardsdatascience.com
towardsdatascience.com
import plotly.express as pximport pandas as pddf = pd.read_csv('https://gist.githubusercontent.com/shinokada/f01139d3a024de375ede23cec5d52360/raw/424ac0055ed71a04e6f45badfaef73df96ad0aad/CrimeStatebyState_1960-2014.csv')df = df[(df['State']!= 'District of Columbia' )]px.choropleth(df,               locations = 'State_code',              color="Murder_per100000",               animation_frame="Year",              color_continuous_scale="Inferno",              locationmode='USA-states',              scope="usa",              range_color=(0, 20),              title='Crime by State',              height=600             )
Line 1–5:
Import plotly.express and pandas. We create a DataFrame using pd.read_csv. We remove the District of Columbia rows under the State column.
Line 7–17:
We instantiate the plotly.graph_objects.choropleth object and set parameters. - location: This parameter sets the coordinates via location IDs or names. We use State_code column values for locations.- color: We use theMurder_per100000 value to change the color of the state.- animation_frame: This allows us to animate and add the play and stop button under the map.- locationmode: determines to match entries in locations to regions on the map. Values are “ISO-3” or “USA-states”. - scope: limits the map to this value. The available scopes are: : 'world', 'usa', 'europe', 'asia', 'africa', 'north america', 'south america'.- rang_color: determines the value of the scale on the right. Use 0 and the max value.- title: is the tile of the map. - height: is the height created map.- color_continuous_scale: We can set any color scheme from the following list.
from textwrap import wrap named_colorscales = px.colors.named_colorscales()print("\n".join(wrap("".join('{:<12}'.format(c) for c in named_colorscales), 96)))# Outputaggrnyl     agsunset    blackbody   bluered     blues       blugrn      bluyl       brwnyl      bugn        bupu        burg        burgyl      cividis     darkmint    electric    emrld       gnbu        greens      greys       hot         inferno     jet         magenta     magmamint        orrd        oranges     oryel       peach       pinkyl      plasma      plotly3     pubu        pubugn      purd        purp        purples     purpor      rainbow     rdbu        rdpu        redor       reds        sunset      sunsetdark  teal        tealgrn     viridisylgn        ylgnbu      ylorbr      ylorrd      algae       amp         deep        dense       gray        haline      ice         matter      solar       speed       tempo       thermal     turbid      armyrose    brbg        earth       fall        geyser      prgn        piygpicnic      portland    puor        rdgy        rdylbu      rdylgn      spectral    tealrose    temps       tropic      balance     curl        delta       edge        hsv         icefire     phase       twilight    mrybm       mygbm
Let’s create an animated choropleth world map. Plotly has sample datasets and we’re going to use the Gapminder.
import plotly.express as px gapminder = px.data.gapminder()display(gapminder)
Output:
import plotly.express as pxgapminder = px.data.gapminder()px.choropleth(gapminder,                             locations="iso_alpha",                             color="lifeExp",              hover_name="country",                animation_frame="year",                  color_continuous_scale='Plasma',                height=600             )
The official website does not have an example of an animated choropleth map, but it is easy to create using animation_frame and setting proper parameters.
Are you inspired to try it for your next project?
Get full access to every story on Medium by becoming a member.