【问题标题】:Updating parameter value with slider (python)使用滑块更新参数值(python)
【发布时间】:2020-04-08 21:41:02
【问题描述】:

我有一个微分方程组。解决方案取决于参数beta。我想创建一个滑块,这样我就可以更改此参数并直接在我的图中显示解曲线的变化。我想我几乎得到它,但我错过了一件。

我的代码

N = 1

#Initial conditions
I0 = 0.01
S0= N - I0

#System of diff. equations
def system(x, t, beta, gamma ):
    I, S = x

    dIdt = (beta/gamma*S-1)*I*gamma
    dSdt = -(beta/gamma*S-1)*I*gamma

    return dIdt, dSdt

#Parameters initial value
beta = 0.03
gamma = 0.017

#Initial cond. vector
y0 = I0, S0

#time grid
t = np.linspace(0, 1300, 1300)

# Solution 
sol = odeint(system, y0, t, args=(beta, gamma))


################ Animations part ##################

fig, ax = plt.subplots()
plt.subplots_adjust(bottom = 0.25)

#solution curves for I and S
infected, = plt.plot(t, sol[:,0])
recovered, = plt.plot(t, sol[:,1])

axbeta = plt.axes([0.125, 0.1, 0.5, 0.05])

sliderbeta = Slider(axbeta, 'beta', 0, 1, valinit=beta)

def update_beta(val):
    beta_value = sliderbeta.val
    ??????????????????????????????????????
    fig.canvas.draw_idle()

sliderbeta.on_changed(update_beta)

plt.show()

我不知道如何获取我的初始 beta 值以及如何将其替换为 beta_value。我想在我放置问号的地方缺少一些行。

【问题讨论】:

    标签: python matplotlib slider


    【解决方案1】:

    您将任何 ODE 集成移出全局范围并将其迁移到更新函数。在Automatically Rescale ylim and xlim in Matplotlib 之后,需要添加命令来计算新的限制并应用它们。

    # line objects for the solution curves for I and S
    infected, = ax.plot([0], [0])
    recovered, = ax.plot([0], [0])
    
    def update_beta(beta):
        # if triggered as call-back it passes the current slider value
        # Solution 
        sol = odeint(system, y0, t, args=(beta, gamma))
        # update the data for I and S
        infected.set_data(t, sol[:,0])
        recovered.set_data(t, sol[:,1])
        # recompute the ax.dataLim
        ax.relim()
        # update ax.viewLim using the new dataLim
        ax.autoscale_view()
        fig.canvas.draw_idle()
    

    最后,要在启动时获得初始图,请在全局范围内调用此更新函数一次

    update_beta(beta)
    

    【讨论】:

    • 我按照你说的做了。它不工作。我的滑块不需要 on_changed 方法?
    • 是的,需要添加 relim+autoscale 才能正常显示。我没有提到的一切都保持原样。
    • 现在可以使用了!谢谢!我还有一个问题:如果我想添加一个按钮,以便在单击它时自动设置 beta 的过渡动画,比如从 0 到 1,该怎么办?除了能够像现在一样手动设置它。我会很高兴有一种方法。
    • 如果 y 轴不断重新缩放,这会很快在视觉上变得混乱。原则上,您可以在更新函数中创建一个循环,并使用暂停或睡眠函数来控制速度。如果转换循环的长度为 1 或 10,则该按钮会发生变化。但我从未尝试过使用 matplotlib 进行类似的操作,因此可能有更好的方法。另请查看 matplotlib.animation。
    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多