Dynamically update a chart line in python

I draw a line using matplotlib and would like to update my line data as soon as new values ​​are created. However, the window does not appear once in the loop. Although the printed line indicates that the loop is running.

Here is my code:

def inteprolate(u,X): ... return XX # generate initial data XX = inteprolate(u,X) #initial plot xdata = XX[:,0] ydata = XX[:,1] ax=plt.axes() line, = plt.plot(xdata,ydata) # If this is in, The plot works the first time, and then pauses # until the window is closed. # plt.show() # get new values and re-plot while True: print "!" XX = inteprolate(u,XX) line.set_xdata(XX[:,0]) line.set_ydata(XX[:,1]) plt.draw() # no window 

How to update my chart in real time when the plt.show() and plt.draw does not update / display the window?

+1
source share
4 answers

You need to call plt.pause in your loop to give gui the ability to handle all the events you gave it. If you do not, you can get a backup and never show your schedule.

 # get new values and re-plot plt.ion() # make show non-blocking plt.show() # show the figure while True: print "!" XX = inteprolate(u,XX) line.set_xdata(XX[:,0]) line.set_ydata(XX[:,1]) plt.draw() # re-draw the figure plt.pause(.1) # give the gui time to process the draw events 

If you want to make an animation, you really need to learn how to use the animation module. To get started, check out this awesome tutorial .

+1
source

I think this toy code clarifies @ardoi's answer:

 import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,2*np.pi,num=100) plt.ion() for i in xrange(x.size): plt.plot(x[:i], np.sin(x[:i])) plt.xlim(0,2*np.pi) plt.ylim(-1,1) plt.draw() plt.clf() 

Edit: The previous code displays a sinusoidal function, animating it on the screen.

0
source

Effective way to do the same as @Alejandro:

 import matplotlib.pyplot as plt import numpy as np plt.ion() x = np.linspace(0,2*np.pi,num=100) y = np.sin(x) plt.xlim(0,2*np.pi) plt.ylim(-1,1) plot = plt.plot(x[0], y[0])[0] for i in xrange(x.size): plot.set_data(x[0:i],y[0:i]) plt.draw() 
0
source

Source: https://habr.com/ru/post/949052/


All Articles