我有一个while函数生成两个数字列表,最后我用matplotlib.pyplot绘制它们。
我在做
while True:
#....
plt.plot(list1)
plt.plot(list2)
plt.show()
但是为了看到进展,我必须关闭绘图窗口。 有没有办法每x秒用新数据刷新它?
答案 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 post,the animation
API或the animation
examples找到更多详情。
答案 1 :(得分:0)