Black Lives Matter. Please consider donating to Black Girls Code today.

Lines on Mapbox in Python

How to draw a line on Map in Python with Plotly.

If you're using Dash Enterprise's Data Science Workspaces, you can copy/paste any of these cells into a Workspace Jupyter notebook.
Alternatively, download this entire tutorial as a Jupyter notebook and import it into your Workspace.
Find out if your company is using Dash Enterprise.

Install Dash Enterprise on Azure | Install Dash Enterprise on AWS

New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Mapbox Access Token and Base Map Configuration

To plot on Mapbox maps with Plotly you may need a Mapbox account and a public Mapbox Access Token. See our Mapbox Map Layers documentation for more information.

To draw a line on your map, you either can use px.line_mapbox() in Plotly Express, or Scattermapbox traces. Below we show you how to draw a line on Mapbox using Plotly Express.

Lines on Mapbox maps using Plotly Express

In [1]:
import pandas as pd

us_cities = pd.read_csv("")
us_cities = us_cities.query("State in ['New York', 'Ohio']")

import as px

fig = px.line_mapbox(us_cities, lat="lat", lon="lon", color="State", zoom=3, height=300)

fig.update_layout(mapbox_style="stamen-terrain", mapbox_zoom=4, mapbox_center_lat = 41,

Lines on Mapbox maps from GeoPandas

Given a GeoPandas geo-data frame with linestring or multilinestring features, one can extra point data and use px.line_mapbox().

In [2]:
import as px
import geopandas as gpd
import shapely.geometry
import numpy as np
import wget

# download a zipped shapefile"")

# open a zipped shapefile with the zip:// pseudo-protocol
geo_df = gpd.read_file("zip://")

lats = []
lons = []
names = []

for feature, name in zip(geo_df.geometry,
    if isinstance(feature, shapely.geometry.linestring.LineString):
        linestrings = [feature]
    elif isinstance(feature, shapely.geometry.multilinestring.MultiLineString):
        linestrings = feature.geoms
    for linestring in linestrings:
        x, y = linestring.xy
        lats = np.append(lats, y)
        lons = np.append(lons, x)
        names = np.append(names, [name]*len(y))
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        names = np.append(names, None)

fig = px.line_mapbox(lat=lats, lon=lons, hover_name=names,
                     mapbox_style="stamen-terrain", zoom=1)