Bring Drag & Drop to Dash with Dashboard Engine. 💫 Learn how at our next webinar!

Updating the basemap in in Plotly's density_mapbox visualization while preserving viewport

Below is a simple Streamlit application that creates a Plotly density_mapbox visualization and provides a checkbox for altering the basemap used. The problem I have is that I would like to perform the basemap update without modifying the current viewport (centerpoint and zoom level). In this code, when you click the checkbox, the plot gets rerendered and the viewport is reset. I’m guessing I need to use Streamlit’s caching functionality to save the current state of the Plotly visualization and use those parameters to reinstantiate the viz with the previous state. The trick is that I’m not sure how to get the current center point and zoom level. Any suggestions on how to do this?

import streamlit as st
import plotly.express as px
import pandas as pd

df = pd.DataFrame(
    data=(
        [
            [32.4087249155, -100.9509696428, "2013-01-01", 1],
            [31.5201976084, -102.1030942593, "2013-01-01", 1],
            [31.434573418, -102.0592907601, "2013-01-01", 1],
            [31.2635930582, -101.95341361, "2013-01-01", 1],
            [31.4287233847, -102.0253840388, "2013-01-01", 1],
            [31.4872286706, -101.5455598032, "2021-01-01", 1],
            [31.5439162579, -101.4833865708, "2021-01-01", 1],
            [31.5439362581, -101.4833065695, "2021-01-01", 1],
            [31.7980713977, -102.0937650441, "2021-01-01", 1],
            [32.02050082, -103.31736372, "2021-01-01", 1],
        ]
    ),
    columns=["Latitude", "Longitude", "Date", "Count"],
)

st.set_page_config(layout="wide")
style = "carto-positron"
sat_view = st.checkbox("Dark view")
if sat_view:
    style = "carto-darkmatter"

fig = px.density_mapbox(
    df,
    lat="Latitude",
    lon="Longitude",
    z="Count",
    radius=10,
    zoom=3,
)
fig.update_layout(mapbox_style=style)

# Display the figure
st.plotly_chart(fig, use_container_width=True)