Open In App

How to update a plot in Matplotlib?

In this article, let’s discuss how to update a plot in Matplotlib. Updating a plot simply means plotting the data, then clearing the existing plot, and then again plotting the updated data and all these steps are performed in a loop. 

Functions Used:

Below is the implementation.






x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)




plt.ion()




fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')




for phase in np.linspace(0, 10*np.pi, 100):
    line1.set_ydata(np.sin(0.5 * x + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()

Complete code.




import matplotlib.pyplot as plt
import numpy as np
  
x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)
  
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')
  
for phase in np.linspace(0, 10*np.pi, 100):
    line1.set_ydata(np.sin(0.5 * x + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()

Output:




Article Tags :