实时Matplotlib图在仍然处于循环中时无法正常工作 [英] Real time matplotlib plot is not working while still in a loop

查看:139
本文介绍了实时Matplotlib图在仍然处于循环中时无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个实时图形绘图程序,该程序从串行端口获取输入.最初,我尝试了很多发布在网站上的代码,但是没有一个起作用.因此,我决定通过整合在网站上看到的代码片段来自行编写代码.但是问题在于,只有在程序结束(即循环外)时,图形才会弹出.在循环中,它什么也没有显示,只是一块空白的画布.我还是python的新手.这是我的代码.

I want to create a real time graph plotting program which takes input from serial port. Initially, I had tried a lot of code that posted on websites, but none of them worked. So, I decided to write code on my own by integrating pieces of code I've seen on the websites. But the problem is the graph will pop out only when the program ends,in other words, out of the loop. While in the loop, it shows nothing, just a blank canvas. I'm still pretty new to python. Here is my code.

import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np

# simulates input from serial port
def random_gen():
    while True:
        val = random.randint(1,10)
        yield val
        time.sleep(0.1)


a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()

line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()

for i in range(0,20):
    a1.appendleft(next(d))
    datatoplot = a1.pop()
    line.set_ydata(a1) 
    plt.draw()
    print a1[0]
    i += 1
    time.sleep(0.1)

我还使用了Enthought Canopy学术许可版本1.1.0.

Also, I use Enthought Canopy academic license ver 1.1.0.

推荐答案

以下是在您的循环中添加此plt.pause(0.0001)的解决方案,如下所示:

Here is the solution add this plt.pause(0.0001) in your loop as below:

import matplotlib.pyplot as plt
import time
import random
from collections import deque
import numpy as np

# simulates input from serial port
def random_gen():
    while True:
        val = random.randint(1,10)
        yield val
        time.sleep(0.1)


a1 = deque([0]*100)
ax = plt.axes(xlim=(0, 20), ylim=(0, 10))
d = random_gen()

line, = plt.plot(a1)
plt.ion()
plt.ylim([0,10])
plt.show()

for i in range(0,20):
    a1.appendleft(next(d))
    datatoplot = a1.pop()
    line.set_ydata(a1)
    plt.draw()
    print a1[0]
    i += 1
    time.sleep(0.1)
    plt.pause(0.0001)                       #add this it will be OK.

这篇关于实时Matplotlib图在仍然处于循环中时无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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