问题应该只出现在IPython中(或者Spyder使用IPython)。问题是
plt.show()
不会阻塞和函数
slide_plot
会回来的。一旦返回,对滑块的所有引用以及因此而产生的回调都将消失。
(中的代码
this linked answer
不使用函数,因此不会出现此问题。)
解决方法是让函数返回对滑块的引用并将其存储。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider
timelines = [np.random.randint(-2, 5, size = 800000),
np.random.randint(-2, 5, size = 800000),
np.random.randint(-2, 5, size = 800000)]
timelines_labels = ["label1", "label2", "label3"]
def slide_plot(timelines, timelines_labels):
f, ax = plt.subplots(len(timelines), 1, sharex = True)
def update(pos):
for k, a in enumerate(ax):
a.axis([pos,pos+25,-max(timelines[k])-1, max(timelines[k])+1])
f.canvas.draw_idle()
f.subplots_adjust(bottom=0.25)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
t = np.arange(0.0, len(timelines[0]), 1)
for k, a in enumerate(ax):
a.plot(t, timelines[k], lw = 0.55, label=timelines_labels[k])
a.legend(loc="upper right")
a.axis([0, 25, -max(timelines[k])-1, max(timelines[k])+1])
ax[-1].set_xticks(np.arange(0.0, len(timelines[0]) / 8000, 10))
axpos = plt.axes([0.2, 0.1, 0.65, 0.03])
spos = Slider(axpos, 'Time (ms)', 0.1, 90.0)
spos.on_changed(update)
plt.show()
return spos
slider = slide_plot(timelines, timelines_labels)
或者,您可以将Spyder配置为不使用Preferences/IPython/graphics下的“matplotlib图形支持”,禁用“激活支持”并启动新的IPython控制台以使其生效。