極簡教程: 使用 matplotlib 繪製 GIF 動圖

開門見山,直接上例子:

clipboard.png

有如下特點:

  • 散點圖的部分是不變的;線是移動的
  • X 軸標題每一禎改變一次

DEMO 的環境

  • Ubuntu 18.04.2 LTS
  • conda 4.6.3
  • Python 3.7.2

創建 virtualenv

ichexw at n3xt-Studio -> conda create --name matplot-gif python=3.7
ichexw at n3xt-Studio -> conda activate matplot-gif

安裝必要的依賴

安裝 matplotlib

(matplotlib-gif) ichexw at n3xt-Studio -> conda install matplotlib

安裝 imagemagick

(matplotlib-gif) ichexw at n3xt-Studio -> conda install -c conda-forge imagemagick

代碼實現

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

# 創建圖層和佈局
fig, ax = plt.subplots()
fig.set_tight_layout(True)

# 查看圖標的尺寸。如果你保存成 gif 的時候,你需要提供 DPI
print('fig size: {0} DPI, size in inches {1}'.format(
    fig.get_dpi(), fig.get_size_inches()))

# 繪製一個散點圖(不會重繪),和初始的線
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = ax.plot(x, x - 5, 'r-', linewidth=2)

def update(i):
    label = 'timestep {0}'.format(i)
    print(label)
    
    # 更新線和座標軸標籤
    line.set_ydata(x - 5 + i)
    ax.set_xlabel(label)
    
    # 返回要重繪的對象
    return line, ax

if __name__ == '__main__':
    # FunAnimation 將會在每一幀執行一次 update
    # frames: 幀數
    # interval: 每幀的間隔
    anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
    if len(sys.argv) > 1 and sys.argv[1] == 'save':
        # 如果第一參數是 save,教會保存成 gif
        # **重點**
        # dpi: 保存的尺寸
        # writer: 使用的渲染器,我們制定成 imagemagick
        anim.save('line.gif', dpi=80, writer='imagemagick')
    else:
        # 否則直接展示
        plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章