Streamlit plotly_chart retain zoom level on callback

Hello!

I am using streamlit to produce some maps using mapbox_scatter. Is there a way to retain the zoom level when the code reruns (e.g. when a user changes one of the filters)? Currently, if I zoom in on the map, then change the ‘layers’ (they’re not layers really), then it defaults back to the initial zoom - see screen snips below

I have used the code below to try and hold the mapbox center and zoom variables in the session state, but I do not think these are overwritten when the maps are zoomed (they seem to just stay as the default -3,55 values)

        if "mapfig" in st.session_state:
            cent = st.session_state.mapfig.layout.mapbox.center
            zoom = st.session_state.mapfig.layout.mapbox.zoom
        else:
            cent = {'lon':-3, 'lat':55}
            zoom = 4.5
            
        st.session_state.mapfig = go.Figure()

# process data to plot

st.session_state.mapfig.add_trace(go.Scattermapbox(lat=lats, lon=lons, mode=lines)
st.session_state.mapfig.update_layout(mapbox={'style':"open-street-map",'center':cent,'zoom':zoom})
st.plotly_chart(st.session_state.mapfig,height=500)


Is there a way to obtain these values directly from Streamlit? Or a way to force the map to maintain it’s zoom limits when it calls back to python?

Many thanks, please ask if more info or details would be helpful!

I am experiencing a similar problem, but in my case I am using an altair_chart instead, please consider below an ilustrative example of code for what I am trying to do:

import streamlit as st
import altair as alt
import pandas as pd


# Dummy data with planets for example
data = pd.DataFrame({
    'wavelength': range(400, 701),
    'flux': [i**0.5 for i in range(400, 701)],
    'planet_id': [i % 4 + 1 for i in range(301)]
})

# List of available planets for selection
planets = [i for i in data['planet_id'].unique()]

# Dropdown for planet selection
selected_planet = st.selectbox(
    'Select a planet:', 
    planets
)

# Filter data based on the selected planet
filtered_data = data[data['planet_id'] == selected_planet]

# Create the chart with zoom range maintained
base_chart = alt.Chart(filtered_data).mark_line().encode(
    x=alt.X('wavelength'),
    y=alt.Y('flux')
).interactive()

# Render the chart
st.altair_chart(base_chart, use_container_width=True)

This code is basically generating a Streamlit web page with a dropdown and graph, where in the latter it is possible to zoom in/out.

Is there a way that the zoom of the graph is maintained (not updated) every time that I select a new planet in the dropdown of my example?
I have been exploring session _state and callbacks concepts, but so far I have not been able to replicate this behaviour in my illustrative example.