1

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)
S P Sharan
  • 1,101
  • 9
  • 18
  • 3
    Does this answer your question? [Automatically Rescale ylim and xlim in Matplotlib](https://stackoverflow.com/questions/10984085/automatically-rescale-ylim-and-xlim-in-matplotlib) – Alex Jan 04 '22 at 14:31
  • Thanks, yes it did! – S P Sharan Jan 04 '22 at 14:50

2 Answers2

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)
S P Sharan
  • 1,101
  • 9
  • 18
0

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)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33