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

Streamlit中Plotly图表on_click点击事件失效问题求助

Streamlit中实现Plotly散点图点击交互的解决方案

问题原因

Streamlit渲染Plotly图表时,会将其转换为静态HTML内容,Plotly原生的Python回调(如on_click)无法被保留并触发,因此直接使用fig.data[0].on_click(click)无效。而早期使用plotly events库出现黑白图,多是由于组件版本兼容问题或未正确传递图表样式配置导致。

可行解决方案

方案1:使用streamlit-plotly-events组件(推荐)

该组件专门为Streamlit与Plotly的交互设计,能正确保留图表样式并捕获点击事件,适配新版Streamlit。

  1. 安装依赖:
pip install streamlit-plotly-events
  1. 修改后的代码:
import streamlit as st
import plotly.express as px
from streamlit_plotly_events import plotly_events

# 准备数据
x = [1,2,3]
y = [4,5,6]
z = [10,11,2]

# 生成散点图
fig = px.scatter(x=x, y=y, size=z)

# 使用plotly_events渲染图表并捕获点击事件
clicked_points = plotly_events(fig, click_event=True, use_container_width=True)

# 处理点击结果
if clicked_points:
    # 获取点击点的索引和对应数据
    point_info = clicked_points[0]
    idx = point_info['pointIndex']
    st.write(f"点击点信息:x={x[idx]}, y={y[idx]}, size={z[idx]}")

方案2:无额外依赖的替代方法(利用Streamlit会话状态)

如果不想安装额外库,可以通过监听图表的选择事件结合会话状态实现,但仅支持点选择而非单点点击:

import streamlit as st
import plotly.express as px

x = [1,2,3]
y = [4,5,6]
z = [10,11,2]

fig = px.scatter(x=x, y=y, size=z)
# 启用选择模式
fig.update_layout(dragmode='select')

# 渲染图表并获取选择数据
selected = st.plotly_chart(fig, use_container_width=True, on_select="rerun")

# 处理选择结果
if selected:
    if selected['selection']['points']:
        idx = selected['selection']['points'][0]['pointIndex']
        st.write(f"选中点信息:x={x[idx]}, y={y[idx]}, size={z[idx]}")

说明

  • 方案1的plotly_events组件能精准捕获单点点击事件,且完全保留Plotly图表的原始样式,解决了黑白图问题。
  • 方案2无需额外依赖,但仅支持框选或点击选择点,交互逻辑略有不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:15:11