matplotlib widgets Slider demo源码讲解

matplotlib widgets Slider demo source code explanation

我正在尝试理解 source code 以便能够使用 matplotlib 的滑块小部件。定义函数 update() 的那段代码真的让我很困扰:

我不明白在 def update(val): 中使用参数 val 有什么意义,val 的值也没有在任何地方引用。 def reset(event): 函数也有同样的问题。到目前为止我已经完成的一些简单测试:

  1. val 参数的名称更改为其他随机词,例如 def update(wtf): 而不更改函数体。生成的代码仍然按预期工作。
  2. 在不改变函数体的情况下向参数添加一些默认值,例如 def update(wtf=None):。生成的代码仍然按预期工作。
  3. 简单地删除参数。 def update():。 Slider NO LONGER 改变情节,这意味着脚本不工作。

我不明白这个 update 函数或 val 参数是如何工作的。有人可以解释一下吗?

is right. Going to the implementation link(逻辑顺序为第 435 行 | 411->425),函数 update 被调用并更新了 Slider 的当前值。但是,不会直接使用传递的值。相反,Slider 的当前值在用户定义的 update 函数中通过全局变量引用直接引用。

on_changed 回调会将滑块的当前值提供给函数。 update 函数因此需要一个参数。示例中未使用此参数的原因是 update 函数需要两个滑块的值,与更改的滑块无关,因此直接从 Slider 实例中获取值。

为了更好地理解滑块的工作方式,可以考虑以下简化版本:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(6*np.pi*t)
l, = plt.plot(t, s, lw=2, color='red')
plt.axis([0, 1, -1.2, 1.2])

axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor="lightblue")
sfreq = Slider(axfreq, 'Freq', 0.1, 20.0, valinit=3)

def update(val):
    l.set_ydata(np.sin(2*np.pi*val*t))
    fig.canvas.draw_idle()

sfreq.on_changed(update)

plt.show()

这里只有一个滑块,值被传递给更新函数,用于计算新的 ydata 值。

非常相似,按钮的 on_click 回调将点击事件传递给函数。这在这种情况下毫无用处,但可以潜在地用于查看使用了哪个鼠标按钮,或者点击发生的确切位置。

def reset(event):
    if event.button == 1:
        sfreq.reset()
        samp.reset()
    else:
        print("Please use the left mouse button")
button.on_clicked(reset)