green and brown map illustration

Animate Choropleth Map with Plotly Express

Utilizing animated maps presents a powerful mechanism to captivate interest and effectively communicate data. Whether you’re a professional crafting a presentation, a journalist curating infographics, or an educator developing classroom material, incorporating animations can significantly enhance audience engagement, concentration, and information retention.

Moreover, the utility extends beyond live animations, as it remains valuable for creating static visuals that span diverse time intervals.


Plotly stands as a data visualization library, offering an extensive range of fundamental visualization charts, statistical graphs, scientific illustrations, financial plots, maps, 3D diagrams, dynamic graphs, and more, catering to diverse visualization needs.

Plotly Express serves as a user-friendly, elevated interface to Plotly. It seamlessly interacts with various datasets, streamlining the process of crafting polished and sophisticated graphs. The choice between Mapbox and Plotly’s inherent mapping capabilities is available for visualization; within this tutorial, we will opt for Plotly’s mapping features.


Animated maps are useful when we want to show a situation or value change in a variety of geographic regions over the course of time.

Loading and Preparing the Data

For convenience, I already have created a CSV file of the required data from a previous prompt with ChatGPT. The file includes columns for the state name, its official abbreviation, the date it entered the union, and the order in which it entered. The file is sorted in ascending order by date.

Note: We’ll load it as a pandas DataFrame because Plotly Express plays very well with pandas.

My request:

Given a dataset containing information about statehood entries, use Python with the libraries NumPy, Pandas, and Plotly Express to analyze and visualize the data. The code provided loads the statehood data from a CSV file named 'statehood_data.csv' and prepares a new 'Year' column by extracting the year from the 'date_entered' column. Display the first 3 rows of the resulting DataFrame."

ChatGPT’s Response:

import numpy as np
import pandas as pd
import plotly.express as px

# Load the statehood data and prepare a "Year" column:
df = pd.read_csv('statehood_data.csv')
df['Year'] = df['date_entered'].str[-4:].astype('int')
df.head(3)

Result:

the head of the DataFrame 

Plotting a Static Choropleth Map Colored by Date of Entry

Generating a choropleth map in Plotly Express is a straightforward process. You can achieve this by utilizing the pre-built choropleth method.

Plotly Express also incorporates a variety of predefined geospatial datasets. To specifically select the dataset for American states, you can utilize parameters like scope, locationmode, and locations.

The ‘abbr’ parameter, in conjunction with the ‘locations’ parameter, corresponds to the official state abbreviation, for instance, ‘CA’ for California and ‘FL’ for Florida.

For color, I initially opted for the Portland color scale. However, if you’re looking for an alternative that is more accommodating to individuals with color vision deficiencies, I recommend considering color scales designed for colorblindness, such as ‘Viridis’.

You can explore the Plotly documentation to discover a variety of available options for color scales that cater to different preferences and accessibility requirements.

My request:

Please provide Python code to createchoropleth map using Plotly Express. for States by Date of Entry into Union dataset in 'statehood_data.csv'+ color blind 

ChatGPT’s Response:

# Plot the DataFrame as a static map with a colorblind-friendly color scale:
fig = px.choropleth(df, 
                    locations='abbr', 
                    locationmode='USA-states', 
                    color='Year', 
                    color_continuous_scale='viridis',  # Use the Viridis color scale
                    scope='usa',
                    hover_data=['state', 'order', 'Year'],
                    title='States by Date of Entry into Union')
fig.update_layout(width=750, height=500)

fig.show()

Result:

The generated map is presently static, lacking animation, yet it offers a range of interactive functionalities. Hovering the cursor over a state triggers a pop-up window displaying its metadata. The upper-right toolbar allows actions such as capturing a screenshot, zooming in and out, panning, selecting via a box, and returning to the “home” view.

The map is a little boring. Let’s inject some liveliness by introducing animation.

Animating by Entry Date

With the addition of a single parameter, “animation_frame,” you can bring animation to the preceding map. In this case, we are animating based on the “data_entered” column, which represents the date a state joined the union.

To ensure that the color bar encompasses the minimum and maximum values of the data, it’s necessary to provide an argument for the “range_color” parameter. Otherwise, the scale will default to the value of the currently displayed state.

This time, I recommend considering color scales designed for colorblindness, such as ‘cividis’, which imparts an antique and “historical” appearance.

My request:

Please provide Python code to create choropleth map using Plotly Express. for States by Date of Entry into Union dataset in 'statehood_data.csv' but this we want to add animation_frame and a color blind set for "historical"  appearance. 

ChatGPT’s Response:

# Plot the Dataframe as an animation showing each state in order of admission:
fig = px.choropleth(df, 
                    locations='abbr', 
                    locationmode='USA-states', 
                    color='Year', 
                    color_continuous_scale='cividis', 
                    scope='usa',
                    hover_data=['state', 'order'],
                    animation_frame='date_entered',
                    range_color= (min(df.Year), max(df.Year)),
                    title='The Date Each State Entered the Union')

fig.update_layout(width=750, height=500)

Result:

To run the animation, either press the play button or use the slider.

The interesting thing here is that the states don’t enter in a logical progression from East to West.

Animating by Entry Year

To see all the states that entered the union in a given year, just change the ‘animation_frame‘ argument to the ‘Year‘ column.

My request:

Please provide Python code to create choropleth map using Plotly Express. for States by Date of Entry into Union dataset in 'statehood_data.csv' just change the animation_frame argument to the Year column 

ChatGPT’s Response:

import pandas as pd
import plotly.express as px
import plotly.io as pio

# Load the statehood data and prepare a "Year" column:
df = pd.read_csv('statehood_data.csv')
df['Year'] = df['date_entered'].str[-4:].astype('int')

# Create an animated choropleth map using Plotly Express:
fig = px.choropleth(df,
                    locations='abbr',
                    locationmode='USA-states',
                    color='Year',
                    color_continuous_scale='cividis',  # Use a colorblind-friendly scale
                    scope='usa',
                    hover_data=['state', 'order', 'Year'],
                    animation_frame=df['Year'],  # Use the 'Year' column for animation
                    title='Historical States by Date of Entry into Union')
fig.update_layout(width=750, height=500)

fig.show()

Result:

Animating Over a Large Timeframe

Four significant timespans in American history that you can use for animating the states by their year of entry into the Union:

  1. 1787-1791: Early Formation and Statehood: This period marks the ratification of the United States Constitution in 1787 and the subsequent admission of the first states into the Union. Delaware, Pennsylvania, New Jersey, Georgia, and Connecticut were among the states that joined during this phase.
  2. 1803-1820: Westward Expansion and Growth: The early 19th century saw rapid westward expansion, with significant events like the Louisiana Purchase in 1803. States such as Louisiana, Ohio, Indiana, and Missouri were admitted to the Union during this time, contributing to the nation’s territorial growth.
  3. 1861-1870: Civil War and Reconstruction: The Civil War era brought about profound changes. States like West Virginia, Nevada, and Nebraska were admitted as the nation grappled with the challenges of the Civil War and the subsequent period of Reconstruction.
  4. 1889-1959: Modernization and 20th Century: The turn of the 20th century witnessed the admission of states like Oklahoma, Arizona, Alaska, and Hawaii. This period reflects the nation’s continued growth, industrialization, and emergence as a global power.

Recommandation done by ChatGPT of course base on the dataset date from 1787 until 1959.

My request:

Please provide Python code to create choropleth map using Plotly Express. for States by Date of Entry into Union dataset in 'statehood_data.csv' just change the new column Timespan. To use it for the animation, change the animation_frame argument to Timespan.

ChatGPT’s Response:

# Animate the states grouped by large timeframes:
conditions = [(df['Year'] >= 1787) & (df['Year'] <= 1791),
              (df['Year'] >= 1803) & (df['Year'] <= 1820),
              (df['Year'] >= 1861) & (df['Year'] <= 1870),
              (df['Year'] >= 1889) & (df['Year'] <= 1959)]

values = ['Early Formation and Statehood', 'Westward Expansion and Growth', 
          'Civil War and Reconstruction', 'Modernization and 20th Century']

df['Timespan'] = np.select(conditions, values)

# Animate the states grouped by year of admission:
fig = px.choropleth(df, 
                    locations='abbr', 
                    locationmode="USA-states", 
                    color='Year', 
                    color_continuous_scale='cividis', 
                    scope="usa",
                    hover_data=['state', 'order'],
                    animation_frame='Timespan',
                    range_color= (min(df.Year), max(df.Year)))
fig.update_layout(width=750, height=500)

# Set the animation speed (in millseconds):
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 2000
fig.show()

Another way, similar than the previous one.

My request:

Please provide Python code to create choropleth map using Plotly Express. for States by Date of Entry into Union dataset in ‘statehood_data.csv’ just change the new column Timespan. To use it for the animation, change the animation_frame argument to Timespan.

ChatGPT’s Response:

# Animate the states grouped by large timeframes:
conditions = [(df['Year'] >= 1787) & (df['Year'] <= 1790),
              (df['Year'] >= 1791) & (df['Year'] <= 1860),
              (df['Year'] >= 1861) & (df['Year'] <= 1900),
              (df['Year'] >= 1901) & (df['Year'] <= 1959)]

values = ['Original 13 Colonies', 'Antebellum Expansion', 
          'Westward Expansion', 'Twentieth Century']

df['Timespan'] = np.select(conditions, values)

# Animate the states grouped by year of admission:
fig = px.choropleth(df, 
                    locations='abbr', 
                    locationmode="USA-states", 
                    color='Year', 
                    color_continuous_scale=px.colors.diverging.Earth, 
                    scope="usa",
                    hover_data=['state', 'order'],
                    animation_frame='Timespan',
                    range_color= (min(df.Year), max(df.Year)))
fig.update_layout(width=750, height=500)

# Set the animation speed (in millseconds):
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 2000
fig.show()

The outcome can vary significantly based on the date range; keep in mind the specific aspects you wish to highlight for the viewers.

In summary,

With just a single parameter, Plotly Express allows you to transform captivating static maps into captivating dynamic maps. Beyond their visual appeal, these animated maps also simplify the identification of outliers within a dataset.

For instance, despite my American background and reasonable historical knowledge, I was taken aback to discover that:

  • Delaware was the initial state to ratify the Constitution, making it the first state in the union (a surprising fact).
  • Maine, despite being part of New England, joined the union relatively late.
  • Oklahoma’s statehood was achieved in the 20th century.
  • Arizona and New Mexico became states only in 1912, despite being involved in the Mexican Cession of 1848.

Exploring other datasets could also prove fascinating, such as ordering states by secession during the American Civil War, by population, or by electoral college votes.

~ Marc FILIAS