Python 实时 matplotlib 图在循环中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19766100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Real time matplotlib plot is not working while still in a loop
提问by Nabs
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.
我想创建一个从串行端口获取输入的实时图形绘图程序。最初,我尝试了很多发布在网站上的代码,但都没有奏效。因此,我决定通过集成我在网站上看到的代码片段来自己编写代码。但问题是只有在程序结束时才会弹出图,换句话说,在循环之外。在循环中,它什么也不显示,只是一个空白画布。我对python还是很陌生。这是我的代码。
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)
Also, I use Enthought Canopy academic license ver 1.1.0.
此外,我使用 Enthought Canopy 学术许可证 1.1.0 版。
采纳答案by Developer
Here is the solution add this plt.pause(0.0001)
in your loop as below:
这是将其添加plt.pause(0.0001)
到循环中的解决方案,如下所示:
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.