Matplotlib实时的pyplot

时间:2014-06-26 13:54:57

标签: python graph matplotlib plot

我有一个while函数生成两个数字列表,最后我用matplotlib.pyplot绘制它们。

我在做

while True:
    #....
    plt.plot(list1)
    plt.plot(list2)
    plt.show()

但是为了看到进展,我必须关闭绘图窗口。 有没有办法每x秒用新数据刷新它?

2 个答案:

答案 0 :(得分:3)

最有效的方法是使用matplotlib.animation。这是一个动画两行的例子,一行代表正弦,另一行代表余弦。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
sin_l, = ax.plot(np.sin(0))
cos_l, = ax.plot(np.cos(0))
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
dx = 0.1

def update(i):
    # i is a counter for each frame.
    # We'll increment x by dx each frame.
    x = np.arange(0, i) * dx
    sin_l.set_data(x, np.sin(x))
    cos_l.set_data(x, np.cos(x))
    return sin_l, cos_l

ani = animation.FuncAnimation(fig, update, frames=51, interval=50)
plt.show()

对于您的特定示例,您将摆脱while True并将while循环中的逻辑放在update函数中。然后,您只需确保set_data而不是进行全新的plt.plot来电。

可在this nice blog postthe animation APIthe animation examples找到更多详情。

答案 1 :(得分:0)

我认为你正在寻找的是"动画"特征。

这是an example

This example是第二个。