Deselecting programmatically selected points on st.plotly_chart

Hi,

My question is regarding selected points on plotly chart, is there a way we can programmatically deselect the points selected by users.

import streamlit as st
import plotly.express as px

df = px.data.iris()  # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")

event = st.plotly_chart(fig, key="iris", on_select="rerun")

event

Thanks.
MMP

Hello,
You can “trick” the deselection by changing the key with a random ‘key’.

import streamlit as st
import plotly.express as px
import hashlib
import time

# Generate a unique hash key based on the current time and user session
def generate_unique_key():
    return hashlib.md5(str(time.time()).encode()).hexdigest()

# Load data and create figure
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length")

# Generate a unique key
unique_key = generate_unique_key()

# Display Plotly chart with unique key
event = st.plotly_chart(fig, key=unique_key, on_select="rerun")

Wow , that’s a clever solution , I will definitely give it a try.

Actually for my use case key is important since I am generating multiple charts with same line of code but different indicators , I will append unique key at the end of indicator name.

event = st.plotly_chart(fig, key= indicatorname_unique_key, on_select="rerun")

Thanks
MMP

1 Like

Hi,

I tried the solution but this way I am unable to catch the selected points by user, issue arises when user selects different points on different charts st.dialog generates warning

                @st.dialog()
                def do_something123(kpi, selected_point):
                   st.write(selected_point)
                       
                
                def catch_event()
                     uniquekey = generate_unique_key()
                     event = st.plotly_chart(fig, key = f'{res}_{technology}_{col}_chart_{uniquekey}', on_select = "rerun")
                        if len(event['selection']['points']) > 0:

                           do_something123(f'{res*emphasized text*}@{col}', event['selection']['points'][0]['x'])

Hi @Faltawer

Can you have a look at my code, I want to return event from user selection from st.plotly_chart, selected points goes to a function decorated with @st.dialog.

Once the event is collected I want to programmatically deselect the selected points , I tried the solution of generating unique key but with that I couldn’t catch the event.

Thanks