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.
JavaScript
x
24
24
1
import time
2
3
import matplotlib.pyplot as plt
4
import numpy as np
5
6
x = np.linspace(0, 10, 100)
7
y = np.sin(x)
8
9
plt.ion()
10
11
figure, ax = plt.subplots(figsize=(10, 8))
12
(line1,) = ax.plot(x, y)
13
14
plt.xlabel("X-axis")
15
plt.ylabel("Y-axis")
16
17
for i in range(1000):
18
new_y = np.sin(x - 0.5 * i) * i
19
line1.set_xdata(x)
20
line1.set_ydata(new_y)
21
figure.canvas.draw()
22
figure.canvas.flush_events()
23
time.sleep(0.1)
24
Advertisement
Answer
Adding ax.relim()
and ax.autoscale()
fixes the issue
JavaScript
1
31
31
1
import time
2
3
import matplotlib.pyplot as plt
4
import numpy as np
5
6
x = np.linspace(0, 10, 100)
7
y = np.sin(x)
8
9
plt.ion()
10
11
ax: plt.Axes
12
figure, ax = plt.subplots(figsize=(10, 8))
13
(line1,) = ax.plot(x, y)
14
ax.autoscale(True)
15
16
plt.xlabel("X-axis")
17
plt.ylabel("Y-axis")
18
19
for i in range(1000):
20
new_y = np.sin(x - 0.5 * i) * i
21
line1.set_xdata(x)
22
line1.set_ydata(new_y)
23
24
# Rescale axes limits
25
ax.relim()
26
ax.autoscale()
27
28
figure.canvas.draw()
29
figure.canvas.flush_events()
30
time.sleep(0.1)
31