How to create a scatter plot on a Mapbox map with Plotly Express

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

A scatter plot on a Mapbox map created with Plotly Express is a visualization that combines the geographical context of a map with the ability to display individual data points as markers. Plotly Express is a high-level data visualization library that allows users to create interactive plots and charts with minimal code.

Features of the scatter plot on a Mapbox map

Some of the key features of scatter plot on a Mapbox map include:

Geographic context: The scatter plot overlaid on a Mapbox map provides a geographical context for the data points. Users can easily interpret the data in relation to specific locations and spatial features.

Interactive exploration: The scatter plot allows users to interact with the map and data points. They can pan and zoom to explore different areas of the map, hover over markers to view tooltips with additional information, and click on markers to trigger custom actions or drill down into specific data subsets.

Customizable markers: Plotly Express allows you to customize the appearance of markers representing data points. You can modify marker size, shape, color, opacity, and text labels based on different data variables. This customization helps to visually encode additional information and highlight patterns or trends within the data.

Marker clustering: When dealing with a large number of data points, it's common to have overlapping markers that can make the plot cluttered. Plotly Express offers built-in marker clustering functionality, automatically grouping nearby markers into clusters. This helps to improve the readability of the plot and provides a more informative overview of the data distribution.

Color mapping: You can assign colors to markers based on a specific data variable, allowing for the visualization of an additional dimension. This color mapping helps to differentiate data points and can represent a numeric or categorical variable.

Size mapping: Similar to color mapping, you can map marker size to a data variable. This feature enables the representation of a third dimension, such as the magnitude or importance of each data point.

Animations: Plotly Express supports the creation of animated scatter plots on Mapbox maps. You can animate the plot to show changes over time or any other sequential variable, providing a dynamic visualization of your data.

Customizable map layout: Plotly Express allows you to customize the map layout by specifying the center coordinates, zoom level, and map style. You can choose from various Mapbox-provided map styles or even use custom map styles created with Mapbox Studio.

Syntax

The scatter_mapbox function syntax typically follows this structure:

import plotly.express as px
fig = px.scatter_mapbox(data_frame, lat='latitude_column',
lon='longitude_column',
hover_data=['additional_variable'],
color='color_variable',
size='size_variable',
zoom=zoom_level,
center=dict(lat=center_lat, lon=center_lon),
mapbox_style='mapbox_style')
Syntax of the scatter_mapbox function

Parameters

The followings are the parameters of scatter_mapbox function:

  • data_frame: The pandas DataFrame or other suitable data structure containing your data.

  • lat: The column name or index representing the latitude values for each data point.

  • lon: The column name or index representing the longitude values for each data point.

  • hover_data: Optional; specify any additional variables to show in tooltips when hovering over markers.

  • color: Optional; specify a column name or index to map marker colors based on a data variable.

  • size: Optional; specify a column name or index to map marker sizes based on a data variable.

  • symbol: Optional; specify a column name or index to map marker symbols based on a data variable.

  • labels: Optional; specify a column name or index to assign text labels to markers.

  • color_continuous_scale: Optional; choose a color scale for continuous color mapping.

  • range_color: Optional; specify the range of values to map to the color scale.

  • color_discrete_sequence: Optional; specify a list of colors to map discrete color values.

  • zoom: Optional; set the initial zoom level of the map.

  • center: Optional; specify the latitude and longitude coordinates to center the map.

  • mapbox_style: Optional; choose a Mapbox map style, such as "open-street-map," "carto-positron," or a custom style created with Mapbox Studio.

  • height: Optional; set the height of the plot in pixels.

  • width: Optional; set the width of the plot in pixels.

Return type

The px.scatter_mapbox() 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 scatter plot, including the data, layout, and style.

Implementation

In the following playground, we create a scatter mapbox using a sample dataset called "carshare" provided by Plotly Express. Used attributes are defined below.

  • centroid_lat: The latitude coordinate of the car share location.

  • centroid_lon: The longitude coordinate of the car share location.

  • car_hours: The number of hours the car is available for sharing at the location.

  • peak_hour: The hour of the day when car-sharing activity is at its peak at the location.

# Import necessary libraries
import plotly.express as px
import pandas as pd

# Load the 'carshare' dataset from Plotly
df = px.data.carshare()

# Display the first five rows of the data
print(df.head())

# Create the scatter plot
fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon", hover_name="car_hours", color="peak_hour", size="car_hours",
                        zoom=10, center=dict(lat=45.5, lon=-73.6), mapbox_style="carto-positron")

# Customize the layout
fig.update_layout(title="Car Share Data on Mapbox Map", mapbox=dict(accesstoken='your_mapbox_token'))

# Display the plot
fig.show()
Create a scatter mapbox of the carshare dataset

Explanation

The code above is explained in detail below:

  • Lines 2–3: 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: Load the Plotly election dataset using the px.data.iris() function and assign it to the variable df. The df variable will now hold the dataset, allowing us to access and analyze its contents.

  • Line 9: 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 inspect the data and verify its structure quickly.

  • Lines 12–13: The function scatter_mapbox takes the DataFrame df as the data source. The lat and lon parameters specify the latitude and longitude columns, respectively. The hover_name parameter determines the information shown when hovering over each marker. The color parameter assigns colors based on the peak_hour column, and the size parameter determines the size of the markers based on the car_hours column.

  • Line 16: Customize the layout of the plot using update_layout() a function. The title parameter sets the plot's title, and the mapbox parameter specifies the Mapbox access token. Please replace 'your_mapbox_token' it with your actual Mapbox access token.

  • Line 19: Display the plot using the fig.show() method, which shows the interactive plot.

Conclusion

Plotly Express to create a scatter plot on a Mapbox map provides a powerful and intuitive way to visualize data with geographic coordinates. By leveraging the features of Plotly Express, such as specifying latitude and longitude columns, customizing hover information, and assigning colors and sizes based on data attributes, we can effectively convey insights and patterns in spatial data. The combination of scatter plots and Mapbox maps offers an interactive and visually appealing representation of data, facilitating the exploration and understanding of geographic patterns and relationships.

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