ในการทำ Animation ของ Seaborn heatmap หรือ correlation matrix เราสามารถทำตามขั้นตอนต่อไปนี้:
- ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
- สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่
- สร้าง tuple มิติ (dimension)
- สร้าง Seaborn heatmap
- สร้างเมธอด init() สำหรับ heatmap แรก
- ใช้คลาส FuncAnimation() เพื่อสร้าง animation โดยการเรียกฟังก์ชัน animate ซ้ำๆ ซึ่งจะสร้างชุดข้อมูลสุ่มและสร้าง heatmap
- เพื่อแสดงรูป ใช้เมธอด show()
ตัวอย่าง
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
dimension = (5, 5)
data = np.random.rand(dimension[0], dimension[1])
sns.heatmap(data, vmax=.8)
def init():
sns.heatmap(np.zeros(dimension), vmax=.8, cbar=False)
def animate(i):
data = np.random.rand(dimension[0], dimension[1])
sns.heatmap(data, vmax=.8, cbar=False)
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=20, repeat=False)
plt.show()
ผลลัพธ์

