从非全局上下文中的回调获取 matplotlib 滑块小部件位置
Obtaining matplotlib slider widget position from callback in non-global context
我想使用 matplotlib 滑块,如在 GUI window(例如 TkInter 等)中的 (下方)中的示例所示。但是,在非全局上下文中,未定义绘图变量 ("spos, fig, ax")。我的理解是,因为 update 被用作回调函数,所以不能或不应该传递参数。
如果是这样,如何在没有全局变量的情况下更新绘图?或
如何在回调函数外获取滑块位置?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(2*np.pi*t)
l, = plt.plot(t,s)
plt.axis([0, 10, -1, 1])
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], axisbg=axcolor)
spos = Slider(axpos, 'Pos', 0.1, 90.0)
def update(val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
spos.on_changed(update)
plt.show()
相关:
1) 另一个 related question 似乎涵盖了这个主题,但似乎没有说明如何获得滑块的位置。
2) A 被问到并用 Slider.set_val() 解决了。在我的情况下,我似乎需要 Slider.get_val() 来代替。
可以向回调函数传递更多参数,例如 functools.partial
def update(data, val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
data['position'] = pos
import functools
data = dict()
spos.on_changed(functools.partial(update, data))
plt.show()
try:
print data['position']
except KeyError:
pass
带有 __call__
方法的 class 也可以用作回调。
我想使用 matplotlib 滑块,如在 GUI window(例如 TkInter 等)中的
如果是这样,如何在没有全局变量的情况下更新绘图?或
如何在回调函数外获取滑块位置?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(2*np.pi*t)
l, = plt.plot(t,s)
plt.axis([0, 10, -1, 1])
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], axisbg=axcolor)
spos = Slider(axpos, 'Pos', 0.1, 90.0)
def update(val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
spos.on_changed(update)
plt.show()
相关:
1) 另一个 related question 似乎涵盖了这个主题,但似乎没有说明如何获得滑块的位置。
2) A
可以向回调函数传递更多参数,例如 functools.partial
def update(data, val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
data['position'] = pos
import functools
data = dict()
spos.on_changed(functools.partial(update, data))
plt.show()
try:
print data['position']
except KeyError:
pass
带有 __call__
方法的 class 也可以用作回调。