Để tạo animation Matplotlib với subplots và ArtistAnimation:
- Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
- Tạo figure và tập subplots.
- Tạo hàm Init vẽ khung trống.
- Dùng FuncAnimation gọi lại hàm *func* liên tục.
- Định nghĩa hàm animate cập nhật dữ liệu trong FuncArtist.
- Hiển thị hình bằng show().
Ví dụ
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'r*')
def init():
ax.set_xlim(0, 100)
ax.set_ylim(-1, 1)
return ln,
def animate(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, animate, init_func=init, blit=True, frames=100)
plt.show()
Kết quả
