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

Hiển thị đồ thị thời gian thực (real-time) trong UI đơn giản Python

Để tạo animation đồ thị thời gian thực (real-time) trong Matplotlib, ta dùng FuncAnimation từ matplotlib.animation.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo dữ liệu 3D (10x10x8 frames).
  • Tạo figure, axes bằng subplots().
  • Định nghĩa hàm animate(i) cập nhật contour frame i.
  • Tạo animation: animation.FuncAnimation(fig, animate, frames=5, interval=100).
  • Hiển thị bằng show() (sẽ ra file GIF animation).

Ví dụ

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.randn(800).reshape(10, 10, 8)
fig, ax = plt.subplots()
def animate(i):
    ax.clear()
    ax.contourf(data[:, :, i], cmap="copper")
ani = animation.FuncAnimation(fig, animate, 5, interval=100, blit=False)
plt.show()

Kết quả

Hiển thị đồ thị thời gian thực (real-time) trong UI đơn giản Python