The following code outputs the selected points upon a user's selection:
import pandas as pd
import numpy as np
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
# Sample data
df = px.data.iris()
# Note output of point selection fails if I uncomment the following line!?
# df = df.assign(sepal_width=np.random.randn(len(df)), sepal_length=np.random.randn(len(df)))
# Create a Plotly figure
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df['sepal_width'],
y=df['sepal_length'],
mode='markers',
))
# Display the figure with selection enabled
selected_points = st.plotly_chart(fig, on_select='rerun')
# Check if points are selected
st.write("Selected points:", selected_points)
# plotly.__version__==5.24.1
# st.__version__==1.42.2
However when I uncomment the df.assign
line, it no longer does so! How can I make plotly+streamlit output the user selected data with my own data?
I believe this is happening because streamlit refreshes the page (and reruns your code) for every interaction, so if you don't set a random seed, the points will change every time you click on a data point.
If you set a random seed beforehand, then the functionality works:
np.random.seed(42)
df = px.data.iris()
df = df.assign(sepal_width=np.random.randn(len(df)), sepal_length=np.random.randn(len(df)))