How to update a plot in Matplotlib?
Last Updated :
17 Mar, 2021
Improve
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:
- canvas.draw(): It is used to update a figure that has been changed. It will redraw the current figure.
- canvas.flush_events(): It holds the GUI event till the UI events have been processed. This will run till the loop ends and values will be updated continuously.
Below is the implementation.
- Creating the data to plot using:
Python3
x = np.linspace( 0 , 10 * np.pi, 100 ) y = np.sin(x) |
- Turn on interactive mode using:
Python3
plt.ion() |
- Now we will configure the plot (the ‘b-‘ indicates a blue line):
Python3
fig = plt.figure() ax = fig.add_subplot( 111 ) line1, = ax.plot(x, y, 'b-' ) |
- And finally, update in a loop:
Python3
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.
Python3
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: