October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Update a Plot in a Loop in Matplotlib (Python)

Create plot artists once, update their data in a loop, and yield to the GUI with plt.pause(); use FuncAnimation for frame-based animation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a quick script, create a plot once, update its artist with methods such as set_data(), and call plt.pause() so the GUI can process events. For a true animation, use FuncAnimation to call an update function for each frame. Rebuilding the plot on every iteration is usually unnecessary.

Update a plot in a simple loop

This pattern suits a short script that repeatedly receives or calculates values and should show them in a desktop plot window:

import matplotlib.pyplot as plt

plt.ion()
fig, ax = plt.subplots()
line, = ax.plot([], [])
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)

x_values, y_values = [], []
for x in range(10):
    x_values.append(x)
    y_values.append(0.8 * (x % 3 - 1))
    line.set_data(x_values, y_values)
    plt.pause(0.1)

plt.ioff()
plt.show()

The line is created once. Each iteration changes the data held by that existing line, then plt.pause(0.1) gives the active figure a chance to update and runs the GUI event loop for the requested interval. The Matplotlib pause API describes it as updating and displaying an active figure before running the event loop.

plt.ion() enables interactive mode; it does not, by itself, make a long-running loop yield to the GUI. The values for the axes in this example are fixed so the plot has a visible range; choose limits that suit your data.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why a plot may update only after the loop ends

A GUI window needs its event loop to handle drawing and input events. If your loop keeps control without yielding, the window may not repaint until the loop finishes. Matplotlib’s interactive figures guide explains how drawing and event processing work together.

For periodic updates, plt.pause(...) is often the simplest way to yield. In an interactive script, you can instead request a redraw and process pending events explicitly:

line.set_ydata(new_y)
fig.canvas.draw_idle()
fig.canvas.flush_events()

draw_idle() schedules a redraw when control returns to the GUI loop; it does not immediately run that loop. flush_events() processes pending GUI events. A plain time.sleep(...) delays Python but does not service the GUI event loop; the Matplotlib pyplot animation example uses plt.pause() for this reason.

Use FuncAnimation for repeated frames

If the goal is an animation rather than manually managing a polling loop, let Matplotlib call an update function for each frame:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 200)
line, = ax.plot(x, np.sin(x))
ax.set_ylim(-1.1, 1.1)

def update(frame):
    line.set_ydata(np.sin(x + frame / 10))
    return (line,)

ani = FuncAnimation(fig, update, frames=100, interval=30, blit=True)
plt.show()

Here, frames supplies the values passed to update, and interval sets the delay between frames in milliseconds. Keep ani referenced while the animation runs: if the animation object is garbage-collected, its timer stops. Matplotlib’s animation API describes FuncAnimation as repeatedly calling a function and recommends updating existing artists rather than creating new ones each frame.

What blitting changes

With blit=True, the callback must return an iterable containing every artist that changed; this example returns the line as a one-item tuple. Blitting can reduce redraw work when only a few artists change. The API notes that blitted artists are drawn on top, so the usual z-order is not respected. If you do not need blitting, omit the argument or use blit=False for a simpler starting point.

When should you clear and redraw the axes?

Calling ax.clear() and plotting everything again can be straightforward when the entire plot changes, but it recreates plot contents and may be slower or flicker. For a changing line, update it with set_data() or set_ydata(); other artist types have their own setter methods. Matplotlib’s animation gallery demonstrates clearing and redrawing as a simple, lower-performance approach.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose the approach for your environment

Situation Approach What to keep in mind
A script periodically polls data or shows progress Update an existing artist in your loop and call plt.pause(...) The active backend and host must support GUI display.
A sequence of animation frames Use FuncAnimation Keep the animation object alive; return changed artists when blitting.
A whole plot must be reconstructed each iteration Clear and redraw the axes Recreating artists can cost more and may flicker.

Display behavior varies between a desktop GUI backend, an IPython shell, a notebook, and a static or non-interactive backend. If a window does not repaint, check that the active backend can open GUI windows and that control is periodically returned to its event loop. Interactive-mode behavior also depends on integration with the host’s event loop, as described in Matplotlib’s interactive-mode API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.