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

Cập nhật tiêu đề biểu đồ (plot title) với Matplotlib animation


Các bước

  1. Thiết lập kích thước hình và padding.
  2. Tạo figure mới.
  3. Tạo dữ liệu x, y bằng numpy.
  4. Lấy trục hiện tại (gca()).
  5. Thêm văn bản vào trục bằng text() (làm tiêu đề động).
  6. Định nghĩa hàm animate(frame) cập nhật văn bản theo frame.
  7. Tạo FuncAnimation.
  8. 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ả

Cập nhật tiêu đề biểu đồ (plot title) với Matplotlib animation