Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีอัปเดต Matplotlib Figure แบบ Dynamic ตามการเปลี่ยนแปลงไฟล์ข้อมูล

การอัปเดตกราฟแบบ Real-time เมื่อไฟล์ข้อมูลเปลี่ยน

ใช้ plt.pause() ในลูปเพื่อ refresh แสดงผลแบบ dynamic

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • กำหนด m, n สำหรับ grid subplots
  • สร้างรายการสีสุ่ม
  • วนลูป clear และ plot ข้อมูลสุ่มใหม่ในแต่ละ subplot
  • ใช้ plt.pause(0.1) หน่วงเวลาและ refresh display
  • แสดงผลด้วย show()

ตัวอย่างโค้ด

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()

คำอธิบาย

plt.pause() รัน GUI event loop ชั่วคราว อนุญาตให้ figure update แสดงผล

หมายเหตุ

สำหรับ production ควรใช้ FuncAnimation หรือ threading แทน