如何在 Matplotlib 中對線圖進行動畫處理?
為了在 matplotlib 中對線圖進行動畫處理,我們可以採取以下步驟 -
使用 subplots() 方法建立一個圖形和一套子圖。
限制 x 和 y 軸的刻度。
使用 numpy 建立 x 和 t 資料點。
從座標向量中返回座標矩陣 X2 和 T2。
使用 plot() 方法透過 x 和 F 資料點繪製一條線。
為了製作動畫圖,更新 y 資料。
透過反覆呼叫函式 *func*、current fig、animate 和 interval 來製作動畫。
使用 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() ax.set(xlim=(-3, 3), ylim=(-1, 1)) x = np.linspace(-3, 3, 91) t = np.linspace(1, 25, 30) X2, T2 = np.meshgrid(x, t) sinT2 = np.sin(2 * np.pi * T2 / T2.max()) F = 0.9 * sinT2 * np.sinc(X2 * (1 + sinT2)) line, = ax.plot(x, F[0, :], color='k', lw=2) def animate(i): line.set_ydata(F[i, :]) anim = animation.FuncAnimation(fig, animate, interval=100, frames=len(t) - 1) anim.save('503.gif') plt.show()
輸出
當我們執行此程式碼時,它將顯示帶動畫的線圖。
廣告