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

查看:233
本文介绍了如何使用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()

请注意一些更改:

  1. 调用plt.pause(0.05)来绘制新数据并运行GUI的事件循环(允许鼠标交互).
  1. Call plt.pause(0.05) to both draw the new data and it runs the GUI's event loop (allowing for mouse interaction).

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

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