Skip to content
Advertisement

Recenter plot after set_xdata and set_ydata

I can use the set_xdata and set_ydata functions to update an existing matplotlib plot. But after updating I want to recenter the plot so that all the points fall into the “view” of the plot.

In the below example, the y data keeps getting bigger but the zoom level of the plot remains same so the data points quickly get out of the scope.

import time

import matplotlib.pyplot as plt
import numpy as np

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

plt.ion()

figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")

for i in range(1000):
    new_y = np.sin(x - 0.5 * i) * i
    line1.set_xdata(x)
    line1.set_ydata(new_y)
    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)

Advertisement

Answer

Adding ax.relim() and ax.autoscale() fixes the issue

import time

import matplotlib.pyplot as plt
import numpy as np

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

plt.ion()

ax: plt.Axes
figure, ax = plt.subplots(figsize=(10, 8))
(line1,) = ax.plot(x, y)
ax.autoscale(True)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")

for i in range(1000):
    new_y = np.sin(x - 0.5 * i) * i
    line1.set_xdata(x)
    line1.set_ydata(new_y)
    
    # Rescale axes limits
    ax.relim()
    ax.autoscale()

    figure.canvas.draw()
    figure.canvas.flush_events()
    time.sleep(0.1)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement