python logo

matplotlib update plot


Python hosting: Host, run, and code Python in the cloud!

Updating a matplotlib plot is straightforward. Create the data, the plot and update in a loop.
Setting interactive mode on is essential: plt.ion(). This controls if the figure is redrawn every draw() command. If it is False (the default), then the figure does not update itself.

Related course:

Update plot example

Copy the code below to test an interactive plot.


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()

matplotlib-update Capture of a frame of the program above

Explanation
We create the data to plot using:


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

Turn on interacive mode using:


plt.ion()

Configure the plot (the ‘b-‘ indicates a blue line):


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

And finally update in a loop:


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

Download Examples
 

BackNext





Leave a Reply:




AstroFloyd 2022-07-12T13:32:33.902Z

below the last line, you need an extra line:


fig.canvas.flush_events()