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?
The problem seems to be that you expect
plt.show()
to show the window and then to return. It does not do that. The program will stop at that point and only resume once you close the window. You should be able to test that: If you close the window and then another window should pop up.To resolve that problem just call
plt.show()
once after your loop. Then you get the complete plot. (But not a 'real-time plotting')You can try setting the keyword-argument
block
like this:plt.show(block=False)
once at the beginning and then use.draw()
to update.None of the methods worked for me. But I have found this Real time matplotlib plot is not working while still in a loop
All you need is to add
and than you could see the new plot.
So your code should look like this, and it will work
I know this question is old, but there's now a package available called drawnow on GitHub as "python-drawnow". This provides an interface similar to MATLAB's drawnow -- you can easily update a figure.
An example for your use case:
python-drawnow is a thin wrapper around
plt.draw
but provides the ability to confirm (or debug) after figure display.If you're interested in realtime plotting, I'd recommend looking into matplotlib's animation API. In particular, using
blit
to avoid redrawing the background on every frame can give you substantial speed gains (~10x):Output:
Here's the working version of the code in question (requires at least version Matplotlib 1.1.0 from 2011-11-14):
Note some of the changes:
plt.pause(0.05)
to both draw the new data and it runs the GUI's event loop (allowing for mouse interaction).If you want draw and not freeze your thread as more point are drawn you should use plt.pause() not time.sleep()
im using the following code to plot a series of xy coordinates.