Fix Python – How do I plot in real-time in a while loop using matplotlib?


Asked By – Chris

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()
    plt.scatter(i, temp_y)
    i += 1

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?

Now we will see solution for issue: How do I plot in real-time in a while loop using matplotlib?


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)

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

This question is answered By – Velimir Mlaker

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0