在 Matplotlib 中建立 D3.js 動畫的動畫 GIF 檔案


為了從D3.js動畫建立動畫 GIF 檔案,我們可以執行以下步驟−

  • 設定圖表大小並調整子圖之間和周圍的填充。
  • 建立一個新的圖表或啟用一個現有的圖表。
  • 將軸新增到當前圖表並使其成為當前軸。
  • 用空列表繪製一條線。
  • 為了初始化線條,傳遞空列表。
  • 為了對正弦曲線進行動畫,更新正弦曲線值並返回線條例項。
  • 使用PillowWriter()類獲得一個電影寫入器例項。
  • 使用PillowWriter儲存 .gif 檔案。

示例

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), 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)

writer = animation.PillowWriter(fps=25)

ani.save("sine.gif", writer=writer)

輸出

更新於:2021 年 8 月 4 日

349 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.