如何始终在中间设置Slider的更新值?

时间:2018-11-12 14:20:07

标签: matplotlib matplotlib-widget

在Matplotlib https://matplotlib.org/gallery/widgets/slider_demo.html的Slider演示之后,我想更新Slider范围,以便每次更改滑块值时,这些值都将重新放在Slider中。

我尝试将滑块定义为

sfreq = Slider(axfreq, 'Freq', freq-10, freq+10, valinit=freq)
samp = Slider(axamp, 'Amp', amp-5, amp+5, valinit=amp)

,但是由于update()函数不返回任何内容,因此不起作用。我还尝试使这些变量在函数内部全局化,但也无法正常工作。我终于尝试在更新功能

中定义滑块
def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()
    Slider(axfreq, 'Freq', freq-10, freq+10, valinit=freq)
    Slider(axamp, 'Amp', amp-5, amp+5, valinit=amp)

但是随着我更改值,这会覆盖越来越多的Sliders。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

因此,我决定使滑块的范围覆盖参数的几个数量级,并以对数刻度显示值。万一有人怀疑,并遵循matplotlib演示:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons

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

axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

sfreq = Slider(axfreq, 'Freq', np.log(1), np.log10(1000), valinit=np.log10(f0), valfmt='%4.2E')
samp = Slider(axamp, 'Amp', a0-5, a0+5, valinit=a0)

def update(val):
    amp = samp.val
    freq = sfreq.val
    sfreq.valtext.set_text('{:4.2E}'.format(10**freq))
    l.set_ydata(amp*np.sin(2*np.pi*10**freq*t))
    fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)

resetax = plt.axes([0.8, 0.025, 0.1, 0.04] )
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

def reset(event):
    sfreq.reset()
    samp.reset()
button.on_clicked(reset)

rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)

def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw_idle()
radio.on_clicked(colorfunc)

plt.show()