如何在 matplotlib.animation 中正確啟用 ffmpeg?
要啟用 **matplotlib.animation 的 ffmpeg**,我們可以採取以下步驟:
設定圖形大小並調整子圖之間和周圍的填充。
設定 **ffmpeg** 目錄。
使用 **figure()** 方法建立一個新的圖形或啟用一個現有的圖形。
將 **'ax1'** 新增到圖形中作為子圖排列的一部分。
根據預先存在的軸繪製分割線。
建立要繪製的隨機資料,以影像形式(即在二維規則光柵上)顯示資料。
為 **ScalarMappable** 例項 **cb** 建立一個顏色條。
將標題設定為當前幀。
製作一個顏色圖列表。
透過重複呼叫函式 animate 來製作動畫。該函式建立新的隨機資料,然後使用 **imshow()** 方法將資料顯示為影像。
獲取基於管道的 **ffmpeg** 寫入器的例項。
儲存當前動畫圖形。
示例
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams['animation.ffmpeg_path'] = 'ffmpeg'
fig = plt.figure()
ax = fig.add_subplot(111)
div = make_axes_locatable(ax)
cax = div.append_axes('right', '5%', '5%')
data = np.random.rand(5, 5)
im = ax.imshow(data)
cb = fig.colorbar(im, cax=cax)
tx = ax.set_title('Frame 0')
cmap = ["copper", 'RdBu_r', 'Oranges', 'cividis', 'hot', 'plasma']
def animate(i):
cax.cla()
data = np.random.rand(5, 5)
im = ax.imshow(data, cmap=cmap[i%len(cmap)])
fig.colorbar(im, cax=cax)
tx.set_text('Frame {0}'.format(i))
ani = animation.FuncAnimation(fig, animate, frames=10)
FFwriter = animation.FFMpegWriter()
ani.save('plot.mp4', writer=FFwriter)輸出
執行程式碼後,它將建立一個名為“plot.mp4”的 mp4 檔案並將其儲存在專案目錄中。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP