且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 matplotlib 在 while 循环中实时绘图?

更新时间:2023-02-20 16:21:48

以下是相关代码的工作版本(至少需要 2011-11-14 的 Matplotlib 1.1.0 版本):

Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):

import numpy as np
import matplotlib.pyplot as plt

plt.axis([0, 10, 0, 1])

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)

plt.show()

注意对 plt.pause(0.05) 的调用,它会绘制新数据并运行 GUI 的事件循环(允许鼠标交互).

Note the call to plt.pause(0.05), which both draws the new data and runs the GUI's event loop (allowing for mouse interaction).