如何使用 matplotlib 在 while 循环中实时绘图? [英] How do I plot in real-time in a while loop using matplotlib?

查看:54
本文介绍了如何使用 matplotlib 在 while 循环中实时绘图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 OpenCV 实时绘制来自相机的一些数据.但是,实时绘图(使用 matplotlib)似乎不起作用.

I am trying to plot some data from a camera in real time using OpenCV. However, the real-time plotting (using matplotlib) doesn't seem to be working.

我已经将问题隔离到这个简单的例子中:

I've isolated the problem into this simple example:

fig = plt.figure()
plt.axis([0, 1000, 0, 1])

i = 0
x = list()
y = list()

while i < 1000:
    temp_y = np.random.random()
    x.append(i)
    y.append(temp_y)
    plt.scatter(i, temp_y)
    i += 1
    plt.show()

我希望这个例子能够单独绘制 1000 个点.实际发生的是,窗口弹出并显示第一个点(没问题),然后等待循环完成,然后填充图形的其余部分.

I would expect this example to plot 1000 points individually. What actually happens is that the window pops up with the first point showing (ok with that), then waits for the loop to finish before it populates the rest of the graph.

有什么想法为什么我没有看到一次填充一个点吗?

Any thoughts why I am not seeing points populated one at a time?

推荐答案

以下是相关代码的工作版本(至少需要 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).

这篇关于如何使用 matplotlib 在 while 循环中实时绘图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆