Các bước
- Thiết lập kích thước hình và padding.
- Tạo figure mới.
- Tạo dữ liệu
x, y bằng numpy.
- Lấy trục hiện tại (
gca()).
- Thêm văn bản vào trục bằng
text() (làm tiêu đề động).
- Định nghĩa hàm
animate(frame) cập nhật văn bản theo frame.
- Tạo
FuncAnimation.
- Gọi
show().
Ví dụ
import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
x = np.linspace(-10, 10, 1000)
y = np.sin(x)
plt.plot(x, y)
ax = plt.gca()
ax.text(0.5, 1.100, "y=sin(x)", bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5},
transform=ax.transAxes, ha="center")
def animate(frame):
ax.text(0.5, 1.100, "y=sin(x), frame: %d" % frame,
bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5},
transform=ax.transAxes, ha="center")
ani = animation.FuncAnimation(fig, animate, interval=100, frames=10, repeat=True)
plt.show()
Kết quả
