Creating a Choropleth plot with Plotly graph objects in Python

Plotly’s graph objects offer an intuitive interface for constructing various visualizations, including Choropleth plots. Choropleth plots, specific to geographical visualizations, represent data by coloring or shading regions based on numerical values, making them effective for understanding spatial distributions. Utilizing Plotly’s capabilities, users can craft interactive and insightful Choropleth maps tailored to their dataset with relative ease.

Features of the Choropleth plot in Plotly graph objects

The Choropleth plot in Plotly’s graph objects is packed with a myriad of features that enhance its functionality and interactivity. Some key features include:

  1. Geographical detail: Users can generate maps from global maps to country-specific regions or states at different levels.

  2. Color scaling: Automatic and customizable color scaling based on the data values allows for easy differentiation of regions.

  3. Interactive hover: Hovering over a region provides detailed information about that specific area, making data interpretation straightforward.

  4. Customizable styling: Users can modify borders, color schemes, and other visual elements to fit specific aesthetic or branding needs.

  5. Projection types: Multiple map projections (e.g., Mercator, Orthographic) can be used depending on the geographical context.

  6. Legend integration: Auto-generated legends explain the color scale, ensuring that the map is readable and interpretable.

  7. Integration with other plot types: Choropleth plots can be integrated or overlaid with other plot types, like scatter plots, for a multi-dimensional data view.

  8. Zoom and pan: Interactivity is further enhanced with zoom and pan functionalities, allowing users to focus on regions of interest.

  9. Scope selection: Users can limit the geographical scope to specific continents or regions to cater to specific audiences or data sets.

  10. Responsive design: The plots are designed to be responsive, making them suitable for various devices and screen sizes.

Syntax

The Choropleth plot syntax typically follows this structure using Plotly graph objects:

import plotly.graph_objects as go
fig = go.Figure(data=go.Choropleth(
locations=['CountryCodes'],
z=[Values],
text=['CountryNames'],
colorscale='Blues',
))
Syntax of the choropleth plot

Parameters

The go.Choropleth object in Plotly has a multitude of parameters to customize our plot. Here are the most commonly used parameters:

  • locations: List or array of values that define the regions on the map. This could be country names, state names, or any identifier defined in the locationmode.

  • z: Data values that determine the color for each region in locations.

  • locationmode: Determines the set of locations used to match entries in locations. Options include:

    • 'ISO-3': Matches locations as country ISO-3166-1 alpha-3 codes.

    • 'USA-states': Matches locations to US state names or abbreviations.

    • 'country names': Matches country names.

  • text: Text displayed when hovering over each region.

  • colorscale: Defines the color scale. There are predefined scales like 'Blues', 'Reds', etc., or we can specify a custom color scale.

  • autocolorscale: It is a boolean value. If true, the color scale is automatically constructed based on the data in z.

  • reversescale: It is a boolean value. If true, it reverses the direction of the color scale.

  • showscale: It is a boolean value. Determines whether or not a colorbar is displayed.

  • colorbar: Object that defines properties of the colorbar, like title, tickvals, etc.

  • marker: Object that defines properties of the region borders, such as:

    • line: Object that defines properties of the lines themselves.

      • color: Color of the borders.

      • width: Width of the borders.

  • hoverinfo: Determines which hover labels to show. We can choose combinations of the data, like 'location+z' to show both location names and z-values.

  • zmin and zmax: Define the range of the color scale.

  • showlegend: It is a boolean value. Determines if the trace legend should be shown or not.

Return type

The go.Choropleth function in Plotly’s graph objects returns a trace object, specifically a Choropleth trace. When combined with go.Figure, it produces a figure object that can be displayed in Jupyter notebooks, rendered as HTML, or exported in various formats. The return type is a data representation for a Choropleth visualization that can be manipulated or displayed as needed.

Implementation

In the following playground, we create a choropleth plot using a sample dataset called “gapminder” provided by Plotly Express. Attributes of gapminder dataset (country, continent, year, lifeExp , pop , gdpPercap and species) defined as follows:

  • country: The name of the country for the data point.

  • continent: The continent to which the country belongs.

  • year: The year in which the data was recorded.

  • lifeExp: The life expectancy of the population in years.

  • pop: The population of the country.

  • gdpPercap: The Gross Domestic Product (GDP) per capita, which is the economic output per person in USD.

  • iso_alpha: The ISO alpha-3 code representing the country.

cd /usercode && python3 main.py
python3 -m http.server 5000 > /dev/null 2>&1 &
Visualize 2007 GDP per Capita worldwide with a choropleth plot using Plotly Graph Objects

Explanation

The code above is explained in detail below:

  • Lines 1–3: We import the necessary modules: plotly.graph_objects for creating custom plots, plotly.express for simplified plotting and pandas for data manipulation.

  • Line 6: We load the gapminder dataset using Plotly Express’s built-in sample dataset.

  • Line 9: We print the first five rows of the loaded dataset using the head() method to inspect the data.

  • Line 12: Filters the df DataFrame to retain only rows where the year column is 2007. This filtered data is stored in a new DataFrame, df_2007.

  • Lines 15–23: Initializes a Choropleth plot using the graph_objects module:

    • locations=df_2007['iso_alpha']: Uses the ISO alpha country codes from the df_2007 dataset for the map's regions.

    • z=df_2007['gdpPercap']: Sets the GDP per capita data as the values to dictate the color intensity on the map.

    • text=df_2007['country']: Displays country names on hover.

    • colorscale='Blues': Uses a blue color scale for the map.

    • marker_line_color and marker_line_width: Define the color and width of the lines separating the regions on the map.

    • colorbar_title: Sets the title for the color bar on the side of the plot.

  • Lines 26–29: Updates the visualization’s layout attributes:

    • title_text: Sets the plot title.

    • geo=dict(...):

      • showframe=False: Hides the frame around the map.

      • showcoastlines=True: Shows the coastlines on the map.

      • projection_type: Sets the map’s projection to 'equirectangular.’

  • Line 31: We display the finalized violin choropleth figure using the show() method.

Conclusion

The Choropleth plot in Plotly’s graph objects offers an interactive and visually engaging way to represent geographical data. Its intuitive interface and vast customization options facilitate the effective portrayal of spatial distributions, such as economic metrics across countries. By leveraging this tool, users can easily transform raw data into insightful geographic visualizations, aiding in better data comprehension and decision-making.


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