萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python Matplotlib 動畫繪製入門:FuncAnimation 核心用法四大範例

Matplotlib 1.1+ 內建 animation.FuncAnimation 支援動態圖表繪製。本文展示四種常見模式:生成器模式、列表幀序列、幀號驅動、自訂資料流更新。

核心 API

ani = animation.FuncAnimation(fig, update_func, frames, init_func=None, interval=200, blit=False)
  • fig:Figure 物件。
  • update_func:每幀呼叫的更新函數,簽名 func(frame_data) 或 func(frame_num, *fargs)。
  • frames:整數(幀數)、可迭代物件(每項傳給 update_func)、或生成器函數。
  • init_func:初始化函數(繪製靜態背景),配合 blit=True 大幅提升效能。
  • interval:幀間隔毫秒數。
  • blit=True:僅重繪變化部分(需 update_func 返回藝術家元組)。

範例 1:生成器模式(無限隨機數據)

import numpy as np, matplotlib.pyplot as plt, matplotlib.animation as animation

fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))

def data_gen():
    while True:
        yield np.random.rand(10)

def update(data):
    line.set_ydata(data)
    return line,

ani = animation.FuncAnimation(fig, update, data_gen, interval=2000)
plt.show()

範例 2:列表幀序列(預設資料)

metric = [
    [0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65],
    [0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55],
    [0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52]
]

line, = ax.plot([1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0])
ani = animation.FuncAnimation(fig, update, metric, interval=2000)

範例 3:幀號驅動(正弦波動畫)

import numpy as np
fig, ax = plt.subplots()
ax.set_xlim(0, 2); ax.set_ylim(-2, 2)
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
plt.show()

範例 4:自訂資料流(動態擴展 X 軸)

def data_gen():
    t = 0
    while t < 100:
        t += 0.05
        yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)

xdata, ydata = [], []
def run(data):
    t, y = data
    xdata.append(t); ydata.append(y)
    if t >= ax.get_xlim()[1]:
        ax.set_xlim(ax.get_xlim()[0], 2*ax.get_xlim()[1])
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)
    return line,

ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10, repeat=False)

效能關鍵

  • 啟用 blit=True 並確保 init_func 繪製靜態背景。
  • 更新函數僅修改必要藝術家屬性(set_data、set_ydata 等)。
  • 大數據量考慮降低幀率或使用 matplotlib.animation.FFMpegWriter 離線渲染存檔。
copyright © 萬盛學電腦網 all rights reserved