Moving X-axis in Matplotlib during real-time plot

To move X-axis in Matplotlib during real-time plot, we can create animations that dynamically adjust the X-axis limits as the plot updates. This technique is useful for creating scrolling plots or zooming effects in real-time data visualization.

Steps to Move X-axis in Real-time Plot

  • Set the figure size and adjust the padding between and around the subplots
  • Create a figure and a set of subplots
  • Create x and y data points using numpy
  • Plot x and y data points using plot() method
  • Make an animation by repeatedly calling a function animate that moves the X-axis during real-time plot
  • To display the figure, use show() method

Example

Here's a complete example that creates a cosine wave and animates the X-axis to show a moving window effect ?

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

x = np.linspace(0, 15, 100)
y = np.cos(x)

ax.plot(x, y, lw=2, color='red')

def animate(frame):
    ax.set_xlim(left=0, right=frame)

ani = animation.FuncAnimation(fig, animate, frames=16, interval=200, repeat=True)

plt.show()

How It Works

The animate() function is called repeatedly with different frame values. Each time it's called, set_xlim() adjusts the X-axis range from 0 to the current frame value, creating a progressive reveal effect of the plotted data.

Creating a Sliding Window Effect

For a sliding window that moves across the data, you can modify the animate function to show a fixed-width window ?

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig, ax = plt.subplots()

x = np.linspace(0, 20, 200)
y = np.sin(x) * np.exp(-x/10)

ax.plot(x, y, lw=2, color='blue')

def animate(frame):
    window_width = 5
    ax.set_xlim(left=frame, right=frame + window_width)

ani = animation.FuncAnimation(fig, animate, frames=150, interval=50, repeat=True)

plt.show()

Key Parameters

Parameter Description Example Value
frames Number of animation frames 16, 150
interval Delay between frames in milliseconds 200, 50
repeat Whether to repeat the animation True/False

Output

The animation creates a dynamic plot where the X-axis progressively reveals the data or slides across it, showing different portions of the plotted function over time.

X-axis (moving window) Y-axis Real-time X-axis Movement Movement Direction

Conclusion

Moving the X-axis in real-time plots is achieved using FuncAnimation and set_xlim(). This technique is essential for creating dynamic visualizations like scrolling charts or progressive data reveals in real-time applications.

Updated on: 2026-03-25T23:48:57+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements