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

在Streamlit中实现可垂直拖拽散点图的技术求助

Streamlit中实现支持垂直拖拽的Plotly散点图

实现方案

Plotly原生不支持垂直拖拽点,但可以通过Streamlit会话状态结合图表选择事件实现,以下是可直接运行的代码:

import streamlit as st
import plotly.graph_objects as go

# 初始化点数据,存到会话状态避免刷新丢失
if 'points' not in st.session_state:
    st.session_state.points = {'x': [1,2,3,4,5], 'y': [3,1,4,2,5]}

# 更新指定x值点的y坐标(垂直拖拽仅修改y)
def update_y(x_val, new_y):
    idx = st.session_state.points['x'].index(x_val)
    st.session_state.points['y'][idx] = new_y

# 创建散点图
fig = go.Figure(go.Scatter(
    x=st.session_state.points['x'],
    y=st.session_state.points['y'],
    mode='markers',
    marker=dict(size=16, color='#1f77b4'),
    hovertemplate='X: %{x}<br>Y: %{y}<extra></extra>'
))

# 固定x轴,确保只能垂直拖拽
fig.update_layout(
    xaxis=dict(range=[0,6], fixedrange=True),
    yaxis=dict(range=[0,6]),
    title='垂直拖拽可交互散点图',
    dragmode='select'
)

# 渲染图表并捕获选择事件
selected = st.plotly_chart(fig, on_select='rerun', key='drag_plot')

# 处理拖拽后的点更新
if selected['selection'] and selected['selection']['points']:
    point = selected['selection']['points'][0]
    update_y(point['x'], point['y'])

# 展示当前所有点的数值
st.subheader('当前点数据')
for x, y in zip(st.session_state.points['x'], st.session_state.points['y']):
    st.write(f'({x}, {y})')

核心细节

  • 利用st.session_state持久化点数据,解决Streamlit页面刷新丢失数据的问题
  • 设置xaxis.fixedrange=True锁定x轴,强制拖拽仅在垂直方向生效
  • 通过on_select='rerun'捕获图表选择事件,实时更新对应点的y值
  • 如果需要更丝滑的拖拽体验,可以自定义Streamlit组件,监听Plotly的plotly_drag原生JS事件实现无刷新更新

内容的提问来源于stack exchange,提问作者Brayan Muñoz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:42:18