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

Cách cập nhật động figure Matplotlib khi file dữ liệu thay đổi?

Để cập nhật figure Matplotlib khi file dữ liệu thay đổi:

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Khởi tạo biến m, n cho số subplot.
  • Tạo danh sách màu để vẽ động.
  • Vẽ điểm dữ liệu động bằng plot() với dữ liệu ngẫu nhiên.
  • Hiển thị hình bằng show().

Ví dụ

import numpy as np
import matplotlib.pyplot as plt
import random
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
m = 2
n = 4
fix, axes = plt.subplots(nrows=m, ncols=n)
hexadecimal_alphabets = '0123456789ABCDEF'
color = ["#" + ''.join([random.choice(hexadecimal_alphabets)
                         for j in range(6)]) for i in range(m*n)]
for i in range(m):
    for j in range(n):
        axes[i][j].clear()
        axes[i][j].plot(np.random.rand(10), np.random.rand(10),
                        color=color[100 % np.random.randint(1, len(color))])
        plt.pause(0.1)
plt.show()

Kết quả

Cách cập nhật động figure Matplotlib khi file dữ liệu thay đổi?