Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Làm mới văn bản (refresh text) trong Matplotlib


Các bước

  1. Thiết lập kích thước hình và padding.
  2. Tạo figure và subplots.
  3. Thêm văn bản vào trục bằng text().
  4. Viết hàm xử lý sự kiện phím 'z' và 'c' để cập nhật văn bản.
  5. Gắn hàm với sự kiện key_press_event.
  6. Vẽ canvas chứa figure.
  7. Tạo animation với ArtistAnimation.
  8. 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ả

Làm mới văn bản (refresh text) trong Matplotlib