You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly+Streamlit自定义数据下无法获取选定点的问题求助

问题描述

原代码结合Plotly与Streamlit实现图表点选输出功能:使用px.data.iris()原始数据时,点选图表中的点能正常输出选中结果;但取消注释df = df.assign(...)行,用随机数据重新生成sepal_width和sepal_length字段后,点选输出功能失效。

解决方案

问题核心是每次Streamlit触发rerun时,都会重新执行np.random.randn()生成全新的随机数据,导致当前渲染的图表点坐标和用户点选时的图表坐标完全不匹配,Streamlit无法关联选中的点。

要解决这个问题,需固定数据生成结果,确保每次rerun时使用同一组数据,两种常用实现方式如下:

方式一:用st.cache_data缓存数据生成逻辑

import pandas as pd
import numpy as np
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go

# 缓存数据生成过程,确保每次rerun调用时返回同一组随机数据
@st.cache_data
def get_data():
    df = px.data.iris()
    df = df.assign(sepal_width=np.random.randn(len(df)), sepal_length=np.random.randn(len(df)))
    return df

df = get_data()

# 创建Plotly图表
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df['sepal_width'],
    y=df['sepal_length'],
    mode='markers',
))

# 启用点选功能并显示图表
selected_points = st.plotly_chart(fig, on_select='rerun')

# 输出选中的点
st.write("选中的点:", selected_points)

# plotly.__version__==5.24.1
# st.__version__==1.42.2

方式二:将数据存入st.session_state

import pandas as pd
import numpy as np
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go

# 仅在首次加载时生成随机数据,后续rerun直接复用session_state中的数据
if 'df' not in st.session_state:
    df = px.data.iris()
    df = df.assign(sepal_width=np.random.randn(len(df)), sepal_length=np.random.randn(len(df)))
    st.session_state['df'] = df

df = st.session_state['df']

# 创建Plotly图表
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df['sepal_width'],
    y=df['sepal_length'],
    mode='markers',
))

# 启用点选功能并显示图表
selected_points = st.plotly_chart(fig, on_select='rerun')

# 输出选中的点
st.write("选中的点:", selected_points)

# plotly.__version__==5.24.1
# st.__version__==1.42.2

内容的提问来源于stack exchange,提问作者user39275

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:46:03