Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Update Matplotlib Animation xlim Dynamically

Use set_xlim in a FuncAnimation callback for a moving x-axis window, or recalculate limits with relim and autoscale_view to fit changing line data.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To move the x-axis as a Matplotlib animation advances, call ax.set_xlim(left, right) inside the FuncAnimation update callback. For a scrolling window that follows the newest x value, use bounds such as x_now - window and x_now. If you instead want the view to fit all data currently in a line, update its data and call ax.relim() followed by ax.autoscale_view().

Move the x-axis with each animation frame

This pattern appends one point per frame and scrolls the x-axis after the data passes the initial window. Adjust the bounds and y-axis limits for your data.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
line, = ax.plot([], [])
xdata, ydata = [], []
window = 10

def init():
    ax.set_xlim(0, window)
    ax.set_ylim(-1, 1)
    return line,

def update(frame):
    xdata.append(frame)
    ydata.append(frame)  # Replace with the value for this frame.
    line.set_data(xdata, ydata)

    # Keep the initial view at 0–window; then follow the newest x value.
    right = max(window, frame)
    left = max(0, right - window)
    ax.set_xlim(left, right)
    return line,

ani = FuncAnimation(fig, update, frames=range(100), init_func=init,
                    blit=False)
plt.show()

The max bounds keep the initial view from shrinking before the animation reaches the window size. For a window that follows a stream without a zero lower bound, use ax.set_xlim(x_now - window, x_now), where x_now is the newest x value. Keep a reference such as ani for the animation’s lifetime: Matplotlib documents that an unreferenced Animation object may be garbage-collected, stopping the animation (Matplotlib animation API, version 3.11.2).

Choose the limit behavior you want

Goal What to do What the x-axis shows
Keep a stable comparison range Set ax.set_xlim(left, right) once and leave autoscaling off. The same fixed range throughout the animation.
Show a moving or scrolling window Call ax.set_xlim(left, right) in each update, deriving the bounds from the current frame or newest x value. A deliberately moving view, such as the most recent 10 x units.
Fit the current line data After line.set_data(...), call ax.relim() and then ax.autoscale_view(). A view recalculated from the artist’s current data.

Recalculate limits from changing line data

Changing a line with set_data does not itself recompute the axes’ data limits. When the line’s current contents should determine the view, recalculate those limits after changing the data:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def update(frame):
    line.set_data(xdata[:frame + 1], ydata[:frame + 1])
    ax.relim()
    ax.autoscale_view()
    return line,

relim() updates the axes’ data limits from artists; autoscale_view() derives the visible view from those limits. Matplotlib’s default margins for x and y are 0.05 (5%), so the displayed range can extend beyond the data extrema. The Matplotlib autoscaling guide, version 3.11.2 explains the distinction between data limits and view limits, as well as the effect of margins.

Calling set_xlim with explicit bounds disables autoscaling by default. Consequently, changing line data later will not expand that fixed view unless you recalculate or re-enable autoscaling. The guide documents Axes.autoscale() as a way to re-enable autoscaling and recalculate limits. For x-only autoscaling, pyplot’s autoscale API accepts axis='x'; its enable argument can enable, disable, or leave autoscaling unchanged. tight=True first sets margins to zero (Matplotlib pyplot autoscale API, version 3.11.1).

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

Blitting when limits change

Begin with blit=False while changing axis limits in the callback. Blitting saves a background and redraws returned animated artists over it; changing the axes limits changes the presentation and can make a cached background stale. That artifact risk follows from Matplotlib’s documented blitting mechanism, rather than a guarantee that every backend will fail in the same way.

If you need blitting for performance, test the exact Matplotlib backend and confirm that limit changes cause an appropriate redraw or background refresh. With blit=True, return the modified artists from the callback; for a single line, return line, is a one-item tuple. Matplotlib also notes that blitted artists appear above other artists regardless of z-order (Matplotlib animation API, version 3.11.2).

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.