『Python』matplotlib實現動畫效果


一般而言,在繪制復雜動畫時,主要借助模塊animation來完成

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.animation import FuncAnimation

# mpl.use("Qt5Agg")

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False  # 解決保存圖像是負號'-'顯示為方塊的問題,或者轉換負號為字符串

fig, ax = plt.subplots(1, 1)

x = np.linspace(0, 2 * np.pi, 5000)
y = np.exp(-x) * np.cos(2 * np.pi * x)
line, = ax.plot(x, y, color="cornflowerblue", lw=3)
ax.set_ylim(-1.0, 1.0)


# to clear current frame
def init():
    line.set_ydata([np.nan] * len(x))
    return line,


# to update the data
def animate(data):
    line.set_ydata(np.exp(-x) * np.cos(2 * np.pi * x + float(data) / 100))
    return line,


# to call class FuncAnimation which connects animate and init
ani = FuncAnimation(fig, animate, init_func=init, frames=200, interval=2, blit=True)

# to save the animation
ani.save("movie.mp4", fps=20, writer="ffmpeg")

plt.show()

下面展示其中的4幀結果

  • line,中的逗號是不能省略的,不然就不是Line2D對象了

  • FuncAnimation的構造函數主要的參數有Figure對象、函數func、幀數frames,幀時間間隔interval


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM