How to keep the zoom level of a graph after refreshing a slider/dropdown

Hi!

I am currently using the interactive capabilities of altair_chart and I am wondering whether it is possible to keep the zoom level every time that a refresh occurs, i.e. a new value in a dropdown or slider is selected.

Please consider below an illustrative example for what I am trying to achieve:

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.

Therefore, in this example I pretended that after selecting a new planet in the dropdown, the zoom area of the chart is mantained.
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.

Thank you very much in advance.

1 Like