How to create a choropleth map with Plotly Express in Python

Plotly Express is a Python library that allows us to create line plots quickly and easily, with customizable parameters and an interactive interface.

A choropleth map is a thematic map that displays divided regions or areas shaded or patterned with a specific data variable. To create a choropleth map using Plotly Express, we typically start with a geographical dataset containing information about regions or countries and their corresponding values.

Features of the choropleth map

Some of the key features of a choropleth map include:

  • High-level interface: Plotly Express provides a high-level interface that simplifies creating choropleth maps. We can generate interactive and visually appealing maps with just a few lines of code.

  • Easy data integration: Choropleth Map in Plotly Express integrates with various data formats, including pandas DataFrames, CSV files, and more. This makes it easy to load and visualize our data.

  • Automatic projection and data alignment: Plotly Express automatically handles the projection and alignment of geographical data. We can specify the location mode (e.g., country names, ISO codes) to ensure accurate data mapping to the corresponding regions.

  • Customizable colors and scales: We can customize the color scheme of our choropleth map using the color_continuous_scale parameter. Plotly Express provides a wide range of predefined color scales, or we can define ourselves. This allows us to represent the range and distribution of values effectively.

  • Hover and click interactions: Choropleth maps created with Plotly Express support hover and click interactions. When we hover over a region, we can display additional information related to that region. Click interactions can be used to implement drill-down functionality or to trigger specific actions.

  • Zoom and pan: Plotly Express choropleth maps have built-in zoom and pan functionality, enabling users to explore the map at different levels of detail. This is particularly useful when visualizing large-scale geographical data.

  • Customizable legends and annotations: We can customize legends and annotations to provide additional context or information about the map. This includes adjusting the position, orientation, and appearance of legends and annotations.

  • Export options: Once we've created our choropleth map, Plotly Express provides options to export the map as an image file or an interactive HTML file. This allows us to share or embed the map in various formats.

Syntax

The choropleth function syntax typically follows the structure below:

import plotly.express as px
fig = px.choropleth(data_frame=df,
locations='location_column',
locationmode='location_mode',
color='color_column',
color_continuous_scale='color_scale',
projection='projection_type')
Syntax of the choropleth function

Parameters

The parameters of choropleth function are as follows:

Required Parameters:

  • data_frame: The DataFrame or GeoDataFrame contains the data for the map.

  • locations: The column in the DataFrame that corresponds to the locations or regions for which we have data.

Optional Parameters:

  • locationmode: This is the mode in which the locations are specified. It can be one of the following values: 'ISO-3', 'USA-states', 'country names', 'geojson-id', 'geojson-feature'.

  • color: This is the column in the DataFrame that contains the values to be visualized on the map.

  • color_continuous_scale: This is the color scale to use for the choropleth map. It can be a built-in Plotly Express color scale (e.g., 'Viridis', 'YlOrRd', 'Blues') or a custom color scale.

  • projection: This is the type of map projection to use. It can be one of the following values: 'equirectangular', 'mercator', 'orthographic', 'natural earth', 'kavrayskiy7', 'miller', 'robinson', 'eckert4', 'azimuthal equal area', 'azimuthal equidistant', 'conic equal area', 'conic conformal', 'conic equidistant', 'gnomonic', 'stereographic', 'mollweide', 'hammer', 'transverse mercator', 'albers usa', 'winkel tripel', 'aitoff', 'sinusoidal'.

  • title: This is the title of the choropleth map.

  • hover_data: These are the columns from the DataFrame to be displayed in the hover tooltip when interacting with the map.

  • labels: This is a dictionary that maps column names to labels for use in hover template formatting.

  • center: These are the center coordinates of the map view, specified as a tuple of latitude and longitude values.

  • scope: This is the scope of the map view. It can be a country name (e.g., 'usa') or a continent name (e.g., 'europe').

Return type

The px.choropleth() function returns a Plotly figure object that can be displayed with fig.show(). The figure object contains all the information required to produce the 3D line plot, including the data, layout, and style.

Implementation

In the following playground, we'll create a choropleth map using a sample dataset called "gapminder" provided by Plotly Express. Used attributes (iso_alpha, gdpPercap, country, and year) defined as follows:

  • iso_alpha: This attribute represents the ISO alpha codes for different locations, such as countries or regions. It is used as a unique identifier for each location in the dataset.

  • gdpPercap: This attribute denotes the GDP per capita, representing the income per person in a specific location. It provides a measure of the economic prosperity or wealth of a country or region.

  • country: This attribute contains the names of countries or regions represented in the dataset. It serves as a label or identifier for each specific location.

  • year: This attribute represents the specific year or period for which the data is recorded. It allows for analysis or visualization of variable changes over time, providing a temporal dimension to the dataset.

cd /usercode && python3 main.py
python3 -m http.server 5000 > /dev/null 2>&1 &
Create a choropleth map of the election dataset

Explanation

The code above is explained in detail below:

  • Lines 2–3: We'll import the required libraries for the code: plotly.express as px for creating the box plot, and pandas as pd for handling data in a DataFrame.

  • Line 6: We'll load the Plotly "gapminder" dataset using the px.data.gapminder() function and assigns it to the variable df. The df variable will now hold the dataset, allowing us to access and analyze its contents.

  • Line 9: We'll print the first five rows of the loaded dataset. The head() function retrieves the top rows of the DataFrame and print() displays the result in the console. It helps to quickly inspect the data and verify its structure.

  • Lines 12–19: To create a choropleth map with Plotly Express, we use the px.choropleth() function, providing several parameters. The df parameter represents the DataFrame holding the data, while locations specifies the column with ISO alpha location codes. color designates the column for mapping values like GDP per capita. hover_name indicates the column with labels displayed on hover, often country names. animation_frame determines the column for animating the map, typically representing time intervals. title sets the map's title, labels allows label customization with a dictionary, and color_continuous_scale determines the color scale used.

  • Line 22: We'll display the plot using the fig.show() method, which shows the interactive plot.

Conclusion

The choropleth map feature of Plotly Express offers a user-friendly and efficient solution for visualizing geospatial data. Users can create interactive and visually appealing maps with minimal code that effectively represent variable distribution across regions. Plotly Express seamlessly integrates with different data formats, making data loading and visualization hassle-free. Customizable options for color scales, legends, annotations, and layout settings enable users to tailor the map to their specific needs. Choropleth maps facilitate geographical data exploration and analysis with hover interactions, zooming, and panning.

Unlock your potential: Plotly Graphing and Visualization series, all in one place!

To deepen your understanding of data visualization using Plotly, explore our comprehensive Answer series below:

Plotly express: quick and intuitive visualization

Plotly Graph Objects: Customization and advanced features

Free Resources

HowDev By Educative. Copyright ©2025 Educative, Inc. All rights reserved