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


Solution 1:[1]

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)

Solution 2:[2]

np.sin(x - 0.5 * i) has multiplied by i, which can be 1000. One alternative is to make the y-axis have a limit greater than 1000. So, you can include plt.ylim([-1100,1100]):

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")
plt.ylim([-1100,1100])

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S P Sharan
Solution 2 BrokenBenchmark