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

Jupyter中如何通过滑块/下拉菜单交互更新函数参数动态刷新绘图

Python函数参数交互+自动重绘实现方案

在Jupyter Notebook/Lab环境下用ipywidgets库就能快速实现需求,不需要改动原有核心计算逻辑,具体步骤如下:

前置准备

先安装依赖库,在终端执行命令:

pip install ipywidgets matplotlib pandas

注:如果使用旧版Jupyter Notebook,安装完成后需要执行jupyter nbextension enable --py widgetsnbextension启用控件扩展,新版Jupyter Lab/Notebook会自动启用,不需要额外操作。

代码调整

首先把原有代码里的转义字符&替换为正常的逻辑与运算符&,同时微调绘图函数,避免多次重绘时图形叠加:

import pandas as pd
import matplotlib.pyplot as plt
import ipywidgets as widgets
from ipywidgets import interact

# 原有工具函数微调
def sort_category (category, file_source):
        file = file_source.loc[file_source['Odds Category'] == category]
        return file

def plot_graph (a, b):
    plt.clf() # 清空上次绘制的内容
    plt.plot(a,b)
    plt.xlabel('日期')
    plt.ylabel('当前资金')
    plt.xticks(rotation=45)
    plt.tight_layout() # 自动调整布局避免标签被截断
    plt.show()

控件配置与绑定

用@interact装饰器给每个入参匹配对应控件,直接加在calcul函数定义上方即可,每个参数的控件配置规则:

  • 数值类参数可通过IntSlider/FloatSlider生成滑块,自定义取值范围、步长、默认值
  • 枚举类参数可通过Dropdown生成下拉菜单,支持直接从数据集读取可选值,不需要手动写死
    完整可运行代码示例:
# 提前加载好你的所有数据源,示例默认放ligue_1,可自行追加其他联赛数据集
data_source_dict = {
    "法甲": ligue_1,
    # "英超": premier_league,
    # "西甲": la_liga
}

@interact(
    bankroll_init = widgets.IntSlider(
        value=10000, # 默认值
        min=1000, # 滑块最小值
        max=50000, # 滑块最大值
        step=1000, # 步长
        description='初始资金' # 控件显示名称
    ),
    bet_init = widgets.IntSlider(
        value=10,
        min=1,
        max=200,
        step=1,
        description='初始投注额'
    ),
    multiplier = widgets.FloatSlider(
        value=2.0,
        min=1.0,
        max=5.0,
        step=0.1,
        description='输局投注乘数'
    ),
    odds_category = widgets.Dropdown(
        # 从数据源里取所有存在的赔率分类作为下拉选项
        options = sorted(ligue_1['Odds Category'].unique()),
        value = 4,
        description='赔率分类'
    ),
    file_source = widgets.Dropdown(
        options = data_source_dict,
        value = ligue_1,
        description='选择联赛数据源'
    )
)
def calcul (bankroll_init, bet_init, multiplier, odds_category, file_source):
    
    sorted_file = sort_category(odds_category, file_source)
    bankroll_current = bankroll_init
    bet_current = bet_init
    list_bankroll = []
    list_date = []

    for i in sorted_file.index:
        
        list_bankroll.append(bankroll_current)
        list_date.append(sorted_file['Date'][i])
        bankroll_current = bankroll_current - bet_current
        
        if (sorted_file['B365H'][i] == sorted_file['Min Odds'][i]) & (sorted_file['FTR'][i] == 'H'):
            bankroll_current = bankroll_current + (bet_current * sorted_file['B365H'][i])
            bet_current = bet_init

        elif (sorted_file['B365A'][i] == sorted_file['Min Odds'][i]) & (sorted_file['FTR'][i] == 'A'):
            bankroll_current = bankroll_current + (bet_current * sorted_file['B365A'][i])
            bet_current = bet_init
        else :
            bet_current = bet_current * multiplier
    
    plot_graph(list_date,list_bankroll)

运行上述代码块后,Notebook里会直接生成对应5个控件,拖动滑块、切换下拉选项时会自动触发函数重新计算,同步刷新下方的资金变化折线图,不需要手动点击运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:06:18