Fix "module 'plotly.express' has no attribute 'scatter_mapbox'" in Plotly 7

Plotly 7 removed scatter_mapbox and the other Mapbox functions. Rename them to scatter_map, map_style and layout.map, drop the access token, and set center along with zoom.

AttributeError: module 'plotly.express' has no attribute 'scatter_mapbox' means you're on Plotly 7, which removed the Mapbox functions. Use px.scatter_map() instead and rename mapbox_style= to map_style=. The new functions draw with MapLibre and need no Mapbox access token, so delete the token too. The code here runs on Plotly 7.2.0 (plotly.js 4.1.1).

Quick Example

This is the error:

fig = px.scatter_mapbox(docks, lat="lat", lon="lon", mapbox_style="carto-positron")
# AttributeError: module 'plotly.express' has no attribute 'scatter_mapbox'

And this is the working Plotly 7 version, with simulated bike-share docks in Madrid:

import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(42)
n = 150
docks = pd.DataFrame({
    "dock": [f"Dock {i:03d}" for i in range(1, n + 1)],
    "lat": 40.4168 + rng.normal(0, 0.016, n),
    "lon": -3.7038 + rng.normal(0, 0.021, n),
    "bikes": rng.integers(0, 28, n),
})

# Plotly 6 and earlier: px.scatter_mapbox(..., mapbox_style="carto-positron")
fig = px.scatter_map(
    docks, lat="lat", lon="lon", color="bikes", hover_name="dock",
    color_continuous_scale="Viridis", map_style="carto-positron",
    title="Bikes available at each dock", height=500,
)
fig.update_traces(marker_size=9)
fig.update_layout(margin=dict(l=0, r=0, t=50, b=0))
fig.show()

Plotly scatter map of 150 simulated bike-share docks over central Madrid on a light carto-positron basemap, colored by bikes available from 0 to 27

There is no zoom or center here. Plotly 7 fits the view to the points on its own, which is why the map frames the docks. If you do set zoom, also set center: see the map opens on the ocean below.

Why scatter_mapbox Stopped Working

Plotly moved its tile maps from Mapbox GL to MapLibre GL, an open-source fork that doesn't need an account. It happened over three releases:

Plotly version px.scatter_mapbox px.scatter_map
5.23 and earlier Works (needs a token for Mapbox's own styles) Doesn't exist
5.24 to 6.x Works but is deprecated; 6.5 prints DeprecationWarning: *scatter_mapbox* is deprecated! Use *scatter_map* instead. Works
7.0 and later AttributeError Works

Check what you have with:

import plotly
print(plotly.__version__)

If code fails in one environment and works in another, the two almost certainly have different Plotly versions, often because a fresh pip install plotly pulled in 7.x. The _map functions exist from 5.24 on, so the renamed code runs on 5.24, 6.x and 7.x alike.

Every Mapbox Name and Its Replacement

The fix is mostly mechanical: in each name, mapbox becomes map.

Plotly 6 and earlier Plotly 7
px.scatter_mapbox() px.scatter_map()
px.line_mapbox() px.line_map()
px.density_mapbox() px.density_map()
px.choropleth_mapbox() px.choropleth_map()
go.Scattermapbox go.Scattermap
go.Densitymapbox go.Densitymap
go.Choroplethmapbox go.Choroplethmap
mapbox_style="..." (in px or update_layout) map_style="..."
fig.update_layout(mapbox=dict(...)) fig.update_layout(map=dict(...))
mapbox2, mapbox3 (subplots) map2, map3
fig.update_mapboxes(...) fig.update_maps(...)
make_subplots(specs=[[{"type": "mapbox"}]]) make_subplots(specs=[[{"type": "map"}]])
subplot="mapbox" on a trace subplot="map"
px.set_mapbox_access_token(...), mapbox_accesstoken=... Delete them: no token needed

With graph_objects, the same migration looks like this:

import plotly.graph_objects as go

fig = go.Figure(go.Scattermap(            # was go.Scattermapbox
    lat=docks["lat"], lon=docks["lon"], mode="markers",
    marker=dict(size=8, color=docks["bikes"], colorscale="Viridis"),
    text=docks["dock"],
))
fig.update_layout(
    map=dict(style="open-street-map",     # was mapbox=dict(style=..., accesstoken=...)
             center=dict(lat=40.4168, lon=-3.7038), zoom=11.5),
    margin=dict(l=0, r=0, t=0, b=0),
)

Other Errors You'll See After the Rename

Renaming the function is usually not the last change. These are the Plotly 7.2 messages for the leftover Mapbox names, and the fix for each:

Error Cause Fix
TypeError: scatter_map() got an unexpected keyword argument 'mapbox_style'. Did you mean 'map_style'? Old keyword in a px call map_style=
ValueError: Invalid property specified for object of type plotly.graph_objs.Layout: 'mapbox' (followed by Did you mean "map"?) update_layout(mapbox=...), mapbox_style=, mapbox_accesstoken= map=..., map_style=, delete the token
AttributeError: module 'plotly.graph_objects' has no attribute 'Scattermapbox' Old trace class go.Scattermap
AttributeError: 'Figure' object has no attribute 'update_mapboxes' Old update method fig.update_maps()
ValueError: Unsupported subplot type: 'mapbox' make_subplots specs {"type": "map"}
AttributeError: module 'plotly.express' has no attribute 'set_mapbox_access_token' Token setup code Delete the line
ValueError: Invalid element(s) received for the 'data' property listing 'type': 'scattermapbox' Loading a figure saved as JSON by Plotly 6 Convert the saved figure

Why Does My Map Show Only Ocean After the Rename?

This one doesn't raise an error. Before Plotly 7, px.scatter_mapbox set the map's center to the mean of your points and its zoom to 8, so zoom=12 alone gave you a close-up of the data. Plotly 7's px functions set neither.

When both are unset, plotly.js fits the view to the data instead, controlled by layout.map.fitbounds="locations" (the default). But setting zoom or center turns that fitting off, so zoom=12 with no center zooms in on latitude 0, longitude 0, in the Gulf of Guinea:

# Worked in Plotly 6; in Plotly 7 this shows open water at lat 0, lon 0
fig = px.scatter_map(docks, lat="lat", lon="lon", zoom=12,
                     map_style="carto-positron", title="zoom=12 only")
fig.show()

# Fix: give the center too (or set neither and let Plotly fit the data)
center = {"lat": docks["lat"].mean(), "lon": docks["lon"].mean()}
fig = px.scatter_map(docks, lat="lat", lon="lon", zoom=12, center=center,
                     map_style="carto-positron", title="zoom=12 and center")
fig.show()

Two Plotly maps side by side: with zoom=12 only the map is plain water with no points, and with zoom=12 and center the docks appear over central Madrid

Density and Choropleth Maps

density_mapbox becomes density_map with the same arguments apart from mapbox_style. Here are simulated trip starts around two hotspots, Puerta del Sol (2,000 trips) and Nuevos Ministerios (1,200):

trips = pd.DataFrame({
    "lat": np.concatenate([40.4169 + rng.normal(0, 0.006, 2000),
                           40.4466 + rng.normal(0, 0.008, 1200)]),
    "lon": np.concatenate([-3.7035 + rng.normal(0, 0.008, 2000),
                           -3.6920 + rng.normal(0, 0.010, 1200)]),
})

fig = px.density_map(  # was px.density_mapbox
    trips, lat="lat", lon="lon", radius=4,
    color_continuous_scale="Inferno", map_style="carto-darkmatter",
    title="Bike trip starts", height=500,
)
fig.update_layout(margin=dict(l=0, r=0, t=50, b=0))
fig.show()

Plotly density map on a dark basemap of Madrid with a bright hotspot of trip starts at Puerta del Sol and a smaller one to the north at Nuevos Ministerios

choropleth_mapbox becomes choropleth_map, again taking the same geojson, locations and featureidkey arguments. For country or state maps that don't need street tiles, px.choropleth and px.scatter_geo never used Mapbox and are unchanged; see Plotly geo maps.

Which Map Styles Work Without a Token?

All of them. In Plotly 6, basic, streets, outdoors, light, dark, satellite and satellite-streets were Mapbox styles that needed an access token. Plotly 7's built-in styles are free:

basic, carto-darkmatter, carto-darkmatter-nolabels, carto-positron, carto-positron-nolabels, carto-voyager, carto-voyager-nolabels, dark, light, open-street-map, outdoors, satellite, satellite-streets, streets, white-bg

The old names now point at free tile servers, so they won't look like the Mapbox originals: in Plotly 7.2 streets and outdoors both draw the same tiles as carto-voyager, and satellite-streets uses Esri imagery. This grid also shows the subplot renames, {"type": "map"} and update_maps():

from plotly.subplots import make_subplots

styles = ["carto-positron", "open-street-map", "carto-darkmatter", "carto-voyager"]
fig = make_subplots(rows=2, cols=2, specs=[[{"type": "map"}] * 2] * 2,
                    subplot_titles=styles, horizontal_spacing=0.02, vertical_spacing=0.07)
for i, style in enumerate(styles):
    row, col = i // 2 + 1, i % 2 + 1
    fig.add_trace(go.Scattermap(lat=docks["lat"], lon=docks["lon"], mode="markers",
                                marker=dict(size=6, color="#e8590c")), row=row, col=col)
    fig.update_maps(style=style, row=row, col=col)
fig.update_maps(center=dict(lat=40.4168, lon=-3.7038), zoom=10.5)  # was update_mapboxes
fig.update_layout(height=600, showlegend=False, margin=dict(l=10, r=10, t=40, b=10))
fig.show()

Grid of four Plotly maps of the same Madrid docks with carto-positron, open-street-map, carto-darkmatter and carto-voyager basemaps

How Do I Load a Figure Saved With scatter_mapbox?

A figure written with fig.write_json() or fig.to_dict() on Plotly 6 stores "type": "scattermapbox" and a "mapbox" layout key, and its template has Mapbox entries too. Plotly 7 rejects all of them, so pio.read_json() and go.Figure(spec) fail. This function renames the keys in the saved dict and drops the access token:

import json

RENAMES = {"scattermapbox": "scattermap", "choroplethmapbox": "choroplethmap",
           "densitymapbox": "densitymap"}


def new_name(name):
    name = RENAMES.get(name, name)
    return "map" + name[len("mapbox"):] if name.startswith("mapbox") else name


def mapbox_to_map(obj, key=None):
    """Rename Mapbox traces and layout keys in a figure dict saved by Plotly 6."""
    if isinstance(obj, dict):
        return {new_name(k): mapbox_to_map(v, k) for k, v in obj.items()
                if k != "accesstoken"}
    if isinstance(obj, list):
        return [mapbox_to_map(v) for v in obj]
    if key in ("type", "subplot") and isinstance(obj, str):
        return new_name(obj)
    return obj


# A shortened figure as Plotly 6 saved it
saved = json.loads("""{
  "data": [{"type": "scattermapbox", "subplot": "mapbox", "mode": "markers",
            "lat": [40.4168, 40.4466], "lon": [-3.7038, -3.6920]}],
  "layout": {"mapbox": {"style": "carto-positron", "zoom": 11, "accesstoken": "pk.abc",
                        "center": {"lat": 40.43, "lon": -3.70}},
             "template": {"data": {"scattermapbox": [{"type": "scattermapbox"}]},
                          "layout": {"mapbox": {"style": "light"}}}}
}""")

fig = go.Figure(mapbox_to_map(saved))
print(fig.data[0].type, fig.layout.map.style, fig.layout.map.zoom)
scattermap carto-positron 11

For a file, run json.load() on it first, then pio.write_json(fig, path) to save the converted figure.

Can I Keep Using scatter_mapbox?

Only by staying on Plotly 6: pip install "plotly<7". That's a stopgap for code you can't change yet. It prints deprecation warnings, and figures using Mapbox's own styles still need a token. Since scatter_map works on 5.24 and later, renaming is the better fix, even for a project that has to support Plotly 6 too.

Practical Tips

  • Search your code for mapbox (case-insensitive) rather than fixing one error at a time; every hit needs a change.
  • Set zoom and center together, or neither. With neither, Plotly 7 fits the view to the data.
  • Plotly 7 static exports of tile maps work with Kaleido, as in this post, but the tiles are downloaded at export time, so fig.write_image() needs network access. See exporting static images.

Similar Topics