16

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)

Also, I use Enthought Canopy academic license ver 1.1.0.

Nabs
  • 362
  • 1
  • 3
  • 10

1 Answers1

38

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.
Developer
  • 8,258
  • 8
  • 49
  • 58
  • Thanks a lot! I have been working on this more than a week. It works very well. You help me a lot. I still have one question. This also slows down the input streaming a little bit. Is there a way to obtain the data and plot it independently? Or I have to write different functions for plotting and streaming or buffering? Or the lag time is so little that I can neglect it? – Nabs Nov 04 '13 at 11:53
  • 2
    Yes, this works. No answer really worked for me given [here](http://stackoverflow.com/questions/11874767/real-time-plotting-in-while-loop-with-matplotlib). – Autonomous Jul 30 '15 at 00:03
  • Excellent and very fast. If you want it even faster just take out the time.sleep! Thanks for the suggestion on here, just what I needed. – bretcj7 Jan 26 '17 at 16:05