ในการอัปเดต bar plot แบบไดนามิกใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:
- ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
- สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่
- สร้างลิสต์ของจุดข้อมูลและสี
- พลอตแท่งด้วย data และ colors ใช้เมธอด bar()
- ใช้คลาส FuncAnimation() สร้าง animation โดยเรียกฟังก์ชัน animation ซ้ำๆ ที่ตั้งค่าความสูงของแท่งและ facecolor ของแท่ง
- เพื่อแสดงรูป ใช้เมธอด show()
ตัวอย่าง
import numpy as np
from matplotlib import animation as animation, pyplot as plt, cm
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
data = [1, 4, 3, 2, 6, 7, 3]
colors = ['red', 'yellow', 'blue', 'green', 'black']
bars = plt.bar(data, data, facecolor='green', alpha=0.75)
def animate(frame):
global bars
index = np.random.randint(1, 7)
bars[frame].set_height(index)
bars[frame].set_facecolor(colors[np.random.randint(0, len(colors))])
ani = animation.FuncAnimation(fig, animate, frames=len(data))
plt.show()
ผลลัพธ์
