Pyplot连接到计时器事件?

时间:2014-08-18 18:26:00

标签: python matplotlib plot

我现在的方式与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)])

好,或者我必须在那里传递更多东西,如示例中所示?

1 个答案:

答案 0 :(得分:1)

Matplotlib有一个与后端无关的计时器,它与gui的事件循环集成在一起。看看figure.canvas.new_timer(...)

呼叫签名是一种触摸方式,但它有效。 (如果你的回调函数不带参数或kwargs,你需要明确指定空序列和dicts。)

作为一个最小的例子:

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()