Lesson 30 · Data visualisation in python
Creating Interactive Choropleth Maps with Plotly for Python Geospatial Visualization
In this lesson, you will learn how to make colorful choropleth maps with Plotly. You do not need any previous mapping or Python experience. By the end, you…
- CourseData visualisation in python
- Lesson30 of 34
- Video13 min
- FormatJupyter notebook · 17 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbWelcome to Python Plotly Choropleth Maps!#
In this lesson, you will learn how to make colorful choropleth maps with Plotly.
You do not need any previous mapping or Python experience.
By the end, you will create a real map using COVID-19 data.
Let's start exploring how data comes to life on maps!
import warnings
from statsmodels.tools.sm_exceptions import ConvergenceWarning, ValueWarning
warnings.filterwarnings('ignore', category=ValueWarning)
warnings.filterwarnings('ignore', category=ConvergenceWarning)
warnings.filterwarnings('ignore', category=RuntimeWarning)
warnings.filterwarnings('ignore')
# Let us import basic packages we need for this lesson
import plotly.express as px
import pandas as pd
What is a Choropleth Map?#
A choropleth map colors regions by a number, like population or cases.
These maps are popular for showing trends in cities, countries, or states.
For example, you can see how COVID-19 cases differ country to country.
You only need simple numbers matched to location names or codes.
# Data setup
covid_url = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/jhu/new_cases.csv"
df = pd.read_csv(covid_url)
print(df.shape)
df.head()
# Looking at the columns
print(df.columns.tolist())
# Data preparation
latest = df.tail(1).T.copy()
latest.columns = ['new_cases']
latest = latest.reset_index()
latest = latest.rename(columns={'index':'country'})
latest = latest[latest['country']!='date'] # Skip the 'date' row if present
latest['new_cases'] = pd.to_numeric(latest['new_cases'], errors='coerce')
latest
What data do we need for a choropleth?#
Plotly wants two things:
A location code (like a country name or short code).
A number for coloring, like new cases.
That is all you need for basic maps.
# Rename and check for missing values
latest = latest.dropna()
latest = latest[latest['new_cases'] >= 0]
latest
# Simple visualization of new cases by country
latest.sort_values('new_cases', ascending=False).head(10).plot.barh(x='country', y='new_cases', figsize=(8,5), legend=False, color='skyblue', title='Top 10 Countries: New Daily COVID-19 Cases')
# Making our first choropleth world map!
fig = px.choropleth(latest, locations='country', locationmode='country names', color='new_cases',
color_continuous_scale='Reds', title='New COVID-19 Cases by Country (latest)',
height=500)
fig.show()
What does 'locationmode' mean?#
'country names' lets Plotly match your table's country names to its map shapes.
You can also use codes like ISO-3 (USA, GBR), but names are easier for beginners.
If a country does not appear, check its spelling or code.
# Try custom colors: green to blue
fig2 = px.choropleth(latest, locations='country', locationmode='country names', color='new_cases',
color_continuous_scale='GnBu', title='COVID-19 New Cases (Green to Blue)', height=500)
fig2.show()
# Highlighting certain countries only
countries_of_interest = ['United States', 'India', 'Brazil', 'France', 'Russia']
focus = latest[latest['country'].isin(countries_of_interest)]
fig3 = px.choropleth(focus, locations='country', locationmode='country names', color='new_cases',
color_continuous_scale='Oranges', title='Select Countries: New COVID-19 Cases', height=400)
fig3.show()
# Customizing the color bar and map style
fig4 = px.choropleth(latest, locations='country', locationmode='country names', color='new_cases',
color_continuous_scale='Blues', title='Custom Color Bar and Style', height=500)
fig4.update_layout(coloraxis_colorbar=dict(title='New Cases', tickprefix='', ticks='outside'))
fig4.update_geos(projection_type='natural earth', showland=True, landcolor='lightgray')
fig4.show()
# Making country codes work with Plotly
gapminder = px.data.gapminder().drop_duplicates('country')
gapminder = gapminder.set_index('country', drop=False)
# Some countries in latest may not be in gapminder; get ISO codes stringently
latest['code'] = latest['country'].map(gapminder['iso_alpha'])
latest_with_code = latest.dropna(subset=['code']).copy()
latest_with_code = latest_with_code[latest_with_code['code'].str.len() == 3]
fig5 = px.choropleth(latest_with_code, locations='code', locationmode='ISO-3', color='new_cases',
color_continuous_scale='PuRd', title='Choropleth with ISO-3 Codes', height=500)
fig5.show()
Why not all countries show up?#
Sometimes country names in your data do not match Plotly's database exactly.
Double-check the spelling or try using ISO-3 codes for best results.
Missing data or typos are common reasons for gaps in the map.
# Making a map for US states (mini-project part 1)
df_states = pd.DataFrame({
'state': ['California', 'Texas', 'Florida', 'New York', 'Illinois'],
'cases': [40000, 32000, 28000, 25000, 22000]
})
fig6 = px.choropleth(df_states, locations='state', locationmode='USA-states', color='cases',
color_continuous_scale='OrRd', title='New Cases: Top 5 US States', scope='usa', height=400)
fig6.show()
# Mini-project part 2: Input your own data
states = []
case_counts = []
for i in range(3):
state = input("Enter a US state name: ")
cases = int(input("Enter new case count: "))
states.append(state)
case_counts.append(cases)
df_input = pd.DataFrame({'state': states, 'cases': case_counts})
fig7 = px.choropleth(df_input, locations='state', locationmode='USA-states', color='cases',
color_continuous_scale='BuPu', title='Your Own US States Map', scope='usa', height=380)
fig7.show()
# Optimizing data for mapping: Standardizing names
latest['country'] = latest['country'].str.strip()
latest['country'] = latest['country'].replace({'United States of America': 'United States'})
# Troubleshooting: What if nothing shows up?
if latest.empty: print("No data in the table! Check your previous steps.")
elif latest['country'].nunique() < 2: print("Not enough unique countries to plot.")
else: print("Data looks fine!")
# Extra tip: Save your map to a file
fig.write_html('choropleth_map.html')
# Challenge: Try a new color scale and only display countries with over 1000 new cases
high_cases = latest[latest['new_cases'] > 1000]
fig8 = px.choropleth(high_cases, locations='country', locationmode='country names', color='new_cases',
color_continuous_scale='aggrnyl', title='Countries with over 1000 New Cases', height=400)
fig8.show()
Lesson Recap#
You have explored how to create choropleth maps with Plotly.
You learned where to find data and how to prepare it for mapping.
You tried coloring, customizing, and even making a map with your own data input.
Practice with different data and color scales to build your mapping skills!
Want more?#
Try mapping population, weather, or your own list of numbers next.
If you liked this lesson, please like, subscribe, or share the video.
Thanks for learning and mapping with us!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



