Các bước
- Thiết lập kích thước hình và padding.
- Tạo figure và subplots.
- Thêm văn bản vào trục bằng
text().
- Viết hàm xử lý sự kiện phím 'z' và 'c' để cập nhật văn bản.
- Gắn hàm với sự kiện
key_press_event.
- Vẽ canvas chứa figure.
- Tạo animation với
ArtistAnimation.
- Gọi
show().
Ví dụ
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
text = ax.text(.5, .5, 'First Text')
def action(event):
if event.key == "z":
text.set_text("zoom")
elif event.key == "c":
text.set_text("cool")
fig.canvas.mpl_connect('key_press_event', action)
fig.canvas.draw()
animation = animation.ArtistAnimation(fig, [(text,)])
plt.show()
Kết quả
