zaro

How to Create Interactive Maps with Python Using OpenStreetMap and Plotly?

Published in Python Interactive Mapping 4 mins read

Creating interactive maps in Python with OpenStreetMap and Plotly is straightforward using Plotly Express, a high-level API built on Plotly. This allows you to visualize geographic data points easily on an interactive map background.

Getting Started: Required Libraries

To begin, you'll need to install the necessary Python libraries:

  • Plotly: The main library for creating interactive charts, including maps.
  • Pandas (Optional but recommended): Useful for handling your geographic data (latitude, longitude, and other relevant information).

You can install them using pip:

pip install plotly pandas

Core Function: plotly.express.scatter_mapbox

The primary tool for this task is the scatter_mapbox function from Plotly Express. Using the scatter_mapbox function from Plotly, you can create a scatter plot on an interactive map. This function allows you to plot data points defined by latitude and longitude coordinates directly onto a map background, which can be set to OpenStreetMap.

Here's how you typically use it:

  1. Prepare Your Data: Organize your geographic data (latitude, longitude, and any other data you want to visualize) into a pandas DataFrame or a similar structure.
  2. Call scatter_mapbox: Pass your data and specify the columns for latitude (lat), longitude (lon), and any other mapping you need.
  3. Set Map Style: Crucially, set the mapbox_style parameter to 'open-street-map' to use OpenStreetMap as the background.

Creating Your Interactive Map

Let's walk through the process with a simple example:

Imagine you have data points with latitude, longitude, and some metrics like 'car_hours' and 'peak_hours'.

import plotly.express as px
import pandas as pd

# Sample Data (Replace with your actual data)
data = {'lat': [34.0522, 40.7128, 41.8781, 37.7749],
        'lon': [-118.2437, -74.0060, -87.6298, -122.4194],
        'city': ['Los Angeles', 'New York', 'Chicago', 'San Francisco'],
        'car_hours': [100, 150, 80, 120],
        'peak_hours': [5, 8, 4, 6]}
df = pd.DataFrame(data)

# Create the map
fig = px.scatter_mapbox(
    df,
    lat="lat",          # Set the latitude column
    lon="lon",          # Set the longitude column
    hover_name="city",  # Show city name on hover
    hover_data={"car_hours": True, "peak_hours": True, "lat": False, "lon": False}, # Show specific data on hover
    color="peak_hours", # Colors the points based on peak hours
    size="car_hours",   # Sizes them based on car hours
    color_continuous_scale=px.colors.cyclical.IceFire, # Choose a color scale
    size_max=30,        # Maximum size of points
    zoom=3,             # Initial zoom level
    height=500,         # Height of the map figure
    title="Interactive Map with OpenStreetMap" # Title
)

# Set the map style to OpenStreetMap
fig.update_layout(mapbox_style="open-street-map")

# Customize layout for better appearance
fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})

# Display the map
fig.show()

In this example:

  • We pass the DataFrame df to px.scatter_mapbox.
  • We specify "lat" and "lon" as the columns containing latitude and longitude coordinates for plotting points.
  • The color="peak_hours" parameter colors the markers based on the values in the 'peak_hours' column.
  • The size="car_hours" parameter sizes the markers based on the values in the 'car_hours' column.
  • The mapbox_style="open-street-map" line in fig.update_layout sets the map background to OpenStreetMap.

Customizing Your Interactive Map

Plotly offers extensive customization options:

  • Hover Information: Use hover_name and hover_data to control the information displayed when a user hovers over a point.
  • Color Scales: Modify color_continuous_scale to change how colors are mapped to data values.
  • Point Appearance: Adjust size_max, opacity, symbol etc.
  • Zoom and Center: Use the zoom and center parameters in px.scatter_mapbox to set the initial view.
  • Layout: Use fig.update_layout to adjust margins, title, mapbox specific settings (like bearing, pitch), etc.

Displaying and Saving the Map

Once you have created the fig object:

  • Display in Notebook/Script: Use fig.show() to render the interactive map in a Jupyter Notebook, Google Colab, or display it in your default web browser if running a script.
  • Save as HTML: Use fig.write_html("map.html") to save the map as a standalone HTML file that can be shared and viewed in any web browser, retaining its interactivity.

Summary Table

Feature Plotly Parameter Description
Latitude Column lat Specifies the column for latitude.
Longitude Column lon Specifies the column for longitude.
Map Style mapbox_style="open-street-map" Sets the background map source to OpenStreetMap.
Point Color color Colors points based on a data column.
Point Size size Sizes points based on a data column.
Hover Info hover_name, hover_data Controls tooltip content on hover.
Initial View zoom, center Sets the default zoom level and map center.
Output fig.show(), fig.write_html() Displays or saves the interactive map.

By leveraging plotly.express.scatter_mapbox and setting the mapbox_style to 'open-street-map', you can effectively create dynamic and interactive maps with your geographic data in Python.