Real time matplotlib plot is not working while still in a loop
Question: 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.


Answer: **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.
    

