Để tạo file GIF animated từ animation D3.js, chúng ta có thể thực hiện các bước sau:
- Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
- Tạo figure mới hoặc kích hoạt figure hiện có.
- Thêm axes vào figure hiện tại và làm cho nó thành axes hiện tại.
- Vẽ line với danh sách rỗng.
- Khởi tạo line bằng cách truyền danh sách rỗng.
- Để animate đường cong sin, cập nhật giá trị sin curve và trả về instance line.
- Lấy instance movie writer bằng lớp PillowWriter().
- Lưu file .gif bằng PillowWriter.
Ví dụ
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,
ani = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
writer = animation.PillowWriter(fps=25)
ani.save("sine.gif", writer=writer)
Kết quả

