StreamlitDuplicateElementId: Error with plotly charts in a While True loop

I want a real time dashboard and following the streamlit guide on this closely once I ran into this error. This error was not happening last spring (2024) with the same code, but is now.

I’ve read through related forum pages and have not found anything that works. By trying out various things, I am nearly certain that streamlit is trying to make brand new charts with each loop through the While True instead of just updating the data. The data updates correctly for the KPI elements… but not the plotly elements.

My code is here: IOT-Superpower/streamlit_app_tutorial.py at main · rrbailey27/IOT-Superpower · GitHub

Hey @R113 ,

Might be a quick solve here - Best Practice with Streamlit elements is to assinging a key to each element, be it text, charts, or any other thing - Must give them a unite “key”. This way we ensure that no duplicate Element ID error raises ever.

In Backend - Streamlit when rendering these elements used the element key as html element ID, which cannot be duplicate. And therefore, Streamlit ensures that we do not mess it up.

Hope this quickly resolves your issue.

I appreciate the suggestion. I had tried adding a specified key to st.ploty_chart, e.g.,

st.plotly_chart(fig_h, key=“humidity”)

but the error persists. I think this is what you are suggesting trying.

Streamlit appears to be trying to put a 2nd chart on the dashboard on the second loop through the While True…instead of just updating the existing chart.

May I take another attempt here -
Instead of while loop, does it works for your if you use st.rerun something like this -

    with humid_graph:
        humiddata = data[['ts','humidity']].copy()
        fig_h = px.area(
            humiddata,
            x="ts", 
            y="humidity",
            title="Humidity (%)")
        st.plotly_chart(fig_h)
        
    
    wait_time = 2 # Change to required intervals
    time.sleep(wait_time)
    st.rerun() # <- this is cause the whole application to reload and hence prevent any element duplication.

Or perhaps try using ttl arguement. Ref to this doct - Connect Streamlit to a public Google Sheet - Streamlit Docs

May be cache_data method might solve this.

Apologies for not being able to help here. :slight_smile:

If @Dhruv4 's suggestion doesn’t work, you could also try putting your plotting section into a separate function and wrapping it with @fragment - and then potentially using st.rerun(scope=“fragment”) - as described here:

https://docs.streamlit.io/develop/api-reference/execution-flow/st.fragment

1 Like