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

如何为Python Panel DateRangeSlider添加on_change事件?

问题描述

我正尝试在Python中使用DateRangeSlider选择起止日期,并用Plotly绘制对应图表。当滑块发生变动时,我希望能检测到更新(获取当前选中的日期范围元组),并据此更新图表的X、Y轴范围。请问是否有对应的事件处理器或可使用的回调函数?本质上,我需要在DateRangeSlider变更后,从DataFrame中提取该范围内的数据,再通过Plotly完成绘图。

编辑:补充代码及输出截图

import datetime as dt
import panel as pn
import yfinance as yf

pn.extension()

# Data part
vix_tickers = ['AUDJPY=X']

df = yf.download(vix_tickers,
                 auto_adjust=True, #only download adjusted data
                 progress=False,
            )
df = df[["Close"]]

# Date Range Slider
date_range_slider = pn.widgets.DateRangeSlider(
    name='Date Range Slider',
    sizing_mode="stretch_width",
    margin = [10,40],
    bar_color = "blue",
    start=df.index[0], end=df.index[-1],
    value=(df.index[0], df.index[-1]),
)

# A Plot
import plotly.graph_objs as go

fig = go.Figure()
df.sort_index(ascending=True, inplace=True)

trace = go.Scatter(x=list(df.index), y=list(df.Close))
fig.add_trace(trace)

fig.update_layout(
    dict(
        title="Time series with range slider and selectors",
        xaxis=dict(
            rangeselector=dict(
                buttons=list(
                    [
                        dict(count=1, label="1m", step="month", stepmode="backward"),
                        dict(count=6, label="6m", step="month", stepmode="backward"),
                        dict(count=1, label="YTD", step="year", stepmode="todate"),
                        dict(count=1, label="1y", step="year", stepmode="backward"),
                        dict(step="all"),
                    ]
                )
            ),
            rangeslider=dict(visible=False),
            type="date",
        ),
    )
)
fig.show()

date_range_slider

输出截图


解决方案

你可以利用Panel的回调绑定机制实现滑块变动时自动更新图表,核心是将滑块的value属性与绘图函数绑定,每次滑块值变化时自动触发数据筛选和图表重构。

完整实现代码

import datetime as dt
import panel as pn
import yfinance as yf
import plotly.graph_objs as go

pn.extension()

# 1. 下载并预处理数据
vix_tickers = ['AUDJPY=X']
df = yf.download(vix_tickers, auto_adjust=True, progress=False)
df = df[["Close"]]
df.sort_index(ascending=True, inplace=True)

# 2. 创建日期范围滑块
date_range_slider = pn.widgets.DateRangeSlider(
    name='日期范围选择器',
    sizing_mode="stretch_width",
    margin=[10,40],
    bar_color="blue",
    start=df.index[0], 
    end=df.index[-1],
    value=(df.index[0], df.index[-1]),
)

# 3. 定义绘图回调函数
def update_plot(date_range):
    start_date, end_date = date_range
    # 筛选指定日期范围内的数据
    filtered_df = df.loc[start_date:end_date]
    
    # 生成新的Plotly图表
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=list(filtered_df.index), y=list(filtered_df.Close)))
    
    fig.update_layout(
        title="带范围选择器的时间序列图",
        xaxis=dict(
            rangeselector=dict(
                buttons=[
                    dict(count=1, label="1月", step="month", stepmode="backward"),
                    dict(count=6, label="6月", step="month", stepmode="backward"),
                    dict(count=1, label="年初至今", step="year", stepmode="todate"),
                    dict(count=1, label="1年", step="year", stepmode="backward"),
                    dict(step="all"),
                ]
            ),
            rangeslider=dict(visible=False),
            type="date",
        ),
    )
    return fig

# 4. 绑定滑块与绘图函数,创建交互式面板
interactive_plot = pn.bind(update_plot, date_range=date_range_slider)
panel = pn.Column(date_range_slider, interactive_plot)

# 显示面板
panel.show()

关键说明

  • 使用pn.bind()将滑块的value传递给update_plot函数,滑块值变化时自动触发函数执行
  • 在update_plot中,通过df.loc[start_date:end_date]精准筛选日期范围内的数据,确保只绘制选中区间的内容
  • 最终将滑块和交互式图表组合成Panel列组件,实现整体交互效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:25:14