Matplotlib pyplot 实时绘图
我有一个循环函数,它会生成两个数字列表,最后我用matplotlib.pyplot把它们画出来。
我正在做的事情是:
while True:
#....
plt.plot(list1)
plt.plot(list2)
plt.show()
但是为了看到数据的变化,我必须关闭图表窗口。有没有办法每隔一段时间自动刷新图表,显示新的数据呢?
2 个回答
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
,把那个循环里的逻辑放到 update
函数里。然后,你只需要确保使用 set_data
,而不是每次都重新调用 plt.plot
。
更多详细信息可以在 这篇不错的博客、这个 animation
API,或者 这个 animation
示例 中找到。