Search code examples
pythonmatplotlibwhile-loopreal-time

How do I plot in real-time in a while loop?


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()

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?


Solution

  • 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()
    

    Note the call to plt.pause(0.05), which both draws the new data and runs the GUI's event loop (allowing for mouse interaction).