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?
show
is probably not the best choice for this. What I would do is usepyplot.draw()
instead. You also might want to include a small time delay (e.g.,time.sleep(0.05)
) in the loop so that you can see the plots happening. If I make these changes to your example it works for me and I see each point appearing one at a time.The top (and many other) answers were built upon
plt.pause()
, but that was an old way of animating the plot in matplotlib. It is not only slow, but also causes focus to be grabbed upon each update (I had a hard time stopping the plotting python process).TL;DR: you may want to use
matplotlib.animation
(as mentioned in documentation).After digging around various answers and pieces of code, this in fact proved to be a smooth way of drawing incoming data infinitely for me.
Here is my code for a quick start. It plots current time with a random number in [0, 100) every 200ms infinitely, while also handling auto rescaling of the view:
You can also explore
blit
for even better performance as in FuncAnimation documentation.I know I'm a bit late to answer this question. Nevertheless, I've made some code a while ago to plot live graphs, that I would like to share:
Just try it out. Copy-paste this code in a new python-file, and run it. You should get a beautiful, smoothly moving graph:
Here is a version that I got to work on my system.
The drawnow(makeFig) line can be replaced with a makeFig(); plt.draw() sequence and it still works OK.