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

如何在Streamlit+Plotly中获取绘图选中的垂直跨度x坐标值?

获取Streamlit中Plotly图表的垂直选择区域坐标

核心方案:监听Plotly的plotly_relayout事件

不需要依赖Holoviews,直接通过JavaScript监听Plotly的区域选择/缩放事件,将选中的X轴起始、结束坐标传递给Streamlit。

完整代码示例

import streamlit as st
import plotly.express as px
import pandas as pd

# 生成测试数据(替换成你的业务数据)
df = pd.DataFrame({
    'x': range(100),
    'y': [i**2 for i in range(100)]
})

# 创建基础Plotly图表,强制开启区域选择模式
fig = px.line(df, x='x', y='y')
fig.update_layout(dragmode='select')

# 将图表转为JSON格式,用于前端渲染
fig_json = fig.to_json()

# 自定义HTML+JS,监听Plotly的relayout事件
html_template = f"""
<div id="plot-container"></div>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script>
    // 渲染Plotly图表
    const plot = Plotly.newPlot('plot-container', {fig_json});
    
    // 监听区域选择、缩放等触发的relayout事件
    plot.on('plotly_relayout', function(eventData) {{
        // 提取X轴的起始和结束坐标
        const xStart = eventData['xaxis.range[0]'];
        const xEnd = eventData['xaxis.range[1]'];
        
        // 确保坐标有效,避免初始渲染的空值
        if (xStart !== undefined && xEnd !== undefined) {{
            // 将坐标传递给Streamlit组件
            window.parent.postMessage({{
                type: 'streamlit:setComponentValue',
                value: {{x1: xStart, x2: xEnd}}
            }}, '*');
        }}
    }});
</script>
"""

# 渲染HTML组件并获取返回的坐标值
selected_x_range = st.components.html(html_template, height=550, key='plot_component')

# 展示获取到的坐标
if selected_x_range:
    st.subheader("选中的X轴范围")
    st.markdown(f"- 起始坐标x1:**{selected_x_range['x1']:.2f}**")
    st.markdown(f"- 结束坐标x2:**{selected_x_range['x2']:.2f}**")
    
    # 可选:根据选中范围重新绘制图表(按需启用)
    with st.expander("查看过滤后的图表"):
        filtered_df = df[(df['x'] >= selected_x_range['x1']) & (df['x'] <= selected_x_range['x2'])]
        filtered_fig = px.line(filtered_df, x='x', y='y')
        st.plotly_chart(filtered_fig, use_container_width=True)

关键细节说明

  • dragmode='select':强制Plotly图表进入区域选择模式,用户可直接拖动鼠标选择垂直区域
  • plotly_relayout事件:用户选择区域、缩放图表时都会触发该事件,事件数据中包含xaxis.range[0](起始x)和xaxis.range[1](结束x)
  • postMessage:通过前端JS将坐标值传递给Streamlit组件,Python端直接通过st.components.html的返回值获取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:22:34