与我现在的方式相同 plt.connect('button_press_event', self.on_click) 我想要像 plt.connect('each_five_seconds_event', self.on_timer)
我怎样才能以与我上面展示的最相似的方式实现这一点?
编辑: 我试过了
fig = plt.subplot2grid((num_cols, num_rows), (col, row), rowspan=rowspan,
colspan=colspan)
timer = fig.canvas.new_timer(interval=100, callbacks=[(self.on_click)])
timer.start()
得到了
AttributeError: 'AxesSubplot' object has no attribute 'canvas'
还有,是这个吗
new_timer(interval=100, callbacks=[(self.on_click)])
很好,还是我必须像示例中那样在其中传递更多内容?
请您参考如下方法:
Matplotlib 有一个与 gui 的事件循环集成的后端不可知计时器。看看 figure.canvas.new_timer(...)。
调用签名有点尴尬,但它有效。 (如果你的回调函数不接受参数或 kwargs,你需要明确指定空序列和字典。)
作为一个最小的例子:
import matplotlib.pyplot as plt
def on_timer():
print 'Hi!'
fig, ax = plt.subplots()
# The interval is in milliseconds.
# "callbacks" expects a sequence of (func, args, kwargs)
timer = fig.canvas.new_timer(interval=5000, callbacks=[(on_timer, [], {})])
timer.start()
plt.show()
作为动画 2D 布朗行走的“奇特”示例:
import numpy as np
import matplotlib.pyplot as plt
def on_timer(line, x, y):
x.append(x[-1] + np.random.normal(0, 1))
y.append(y[-1] + np.random.normal(0, 1))
line.set_data(x, y)
line.axes.relim()
line.axes.autoscale_view()
line.axes.figure.canvas.draw()
x, y = [np.random.normal(0, 1)], [np.random.normal(0, 1)]
fig, ax = plt.subplots()
line, = ax.plot(x, y, color='aqua', marker='o')
timer = fig.canvas.new_timer(interval=100,
callbacks=[(on_timer, [line, x, y], {})])
timer.start()
plt.show()
