Streamlit App re-runs the code when changing one parameter

Hello everyone,

I am building a page which let the user to run a query against my database, once I have the data I would like to perform a simple exploratory data analysis of the data. In specific, I have a graph with several simulations and I am trying to display another one where you can isolate one of those simulations.

The problem arise when, at the graph, the user selects the specific simulation they want to visualize. When selecting a different one, the whole code re-runs altering the results and not being capable of viewing the results per simulation on the current run of the code. Is there a solution for this? When I load the data I use the decorator of cache. This is the following code:

@st.cache_data
def load_data():
    # Simulating a heavy data loading process
    df_filtered = ...  # Your data loading logic here
    return df_filtered

df_filtered = load_data()

# Add a dropdown to select the simulation
simulation_options = df_filtered['run'].unique()  # Assuming 'run' is the identifier for different simulations
selected_simulation = st.selectbox('Select Simulation to Display', simulation_options)

# Plot the selected simulation's price
def plot_simulation(selected_simulation, df_filtered):
    # Filter DataFrame based on selected simulation
    filtered_df_simulation = df_filtered[df_filtered['run'] == selected_simulation]
    
    # Create the plot
    fig = go.Figure()

    fig.add_trace(go.Scatter(
        x=filtered_df_simulation['timestep'],
        y=filtered_df_simulation['price'],
        mode='lines',
        name=f'Simulation {selected_simulation}'
    ))

    fig.update_layout(
        title=f"Price Results for Simulation {selected_simulation}",
        xaxis_title="Days",
        yaxis_title="Price",
        plot_bgcolor='rgba(0,0,0,0)',
        paper_bgcolor='rgba(0,0,0,0)',
        font=dict(color='#3DC00E', size=12),
    )
    
    return fig

# Generate and display the plot
fig = plot_simulation(selected_simulation, df_filtered)
st.plotly_chart(fig).

I have seen that other people have encountered this and stated by streamlit that it’s in the process of being updated. Any news on this?

It’s hard to know exactly how you want the code to behave, but you might want to check out st.fragment - Streamlit Docs, which lets you run a function independently from the rest of the app.

You also might consider using st.session_state to track the latest simulation for a given run, as st.session_state will persist even if you change something in your app.