如何在 Matplotlib 中對向量網格圖進行動畫處理?


若要在 matplotlib 中對pcolormesh 進行動畫處理,我們可以採取以下步驟 -

  • 建立一個圖表和一組子圖。

  • 使用 numpy 建立 x、y 和 t 資料點。

  • 建立 X3、Y3 和 T3,從座標向量返回座標矩陣,方法使用網格。

  • 使用 pcolormesh() 方法建立一個具有非規則矩形柵格的偽彩色圖。

  • 使用 colormesh 顏色軸製作一個顏色條。

  • 使用 Animation() 類方法對 pcolormesh 進行動畫處理。

  • 若要顯示圖表,請使用 show() 方法。

示例

import numpy as np
from matplotlib import pyplot as plt, animation
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()
x = np.linspace(-3, 3, 91)
t = np.linspace(0, 25, 30)
y = np.linspace(-3, 3, 91)
X3, Y3, T3 = np.meshgrid(x, y, t)
sinT3 = np.sin(2 * np.pi * T3 / T3.max(axis=2)[..., np.newaxis])
G = (X3 ** 2 + Y3 ** 2) * sinT3
cax = ax.pcolormesh(x, y, G[:-1, :-1, 0], vmin=-1, vmax=1, cmap='Blues')
fig.colorbar(cax)

def animate(i):
   cax.set_array(G[:-1, :-1, i].flatten())

anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1)
anim.save('517.gif')
plt.show()

輸出

更新日期: 2021 年 5 月 11 日

3000+ 瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告