Để tạo animation cho Seaborn heatmap hoặc ma trận tương quan, chúng ta có thể thực hiện các bước sau:
- Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
- Tạo figure mới hoặc kích hoạt figure hiện có.
- Tạo tuple dimension.
- Tạo Seaborn heatmap.
- Tạo phương thức init() cho heatmap đầu tiên.
- Dùng lớp FuncAnimation() để tạo animation bằng cách gọi liên tục hàm animate tạo dataset ngẫu nhiên và heatmap.
- Để hiển thị figure, dùng phương thức show().
Ví dụ
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()
Kết quả

