LoginSignup
0
0

[ GIF ] Matplotlib でムービー作成

Last updated at Posted at 2023-09-20

pythonで動画を作成する方法をメモします.
matplotlib.animationを使用しました.

ライブラリ

import matplotlib.animation as ani
import matplotlib.pyplot as plt

配列を作成

以下の配列 images に画像を格納していく.

images = []

画像をプロット

  • 動画にする画像を作成

画像を連続で表示させることで動画化します.

image = ax.plot(x, y, color = "steelblue")

色を指定しないと画像一枚ごとに線の色が変化してしまう

複数のグラフを重ねることも可能

image_2 = ax.plot(x, y_2, color = "orangered")

※余談ですが, steelblue, orangered が matplotlib のデフォルトカラーに近い気がしています.

タイトル作成

通常通りタイトル設定はできない.

# これだと反映されない
ax.set_title("title t = {}".format(t))

テキスト入力を使用する.

# テキスト入力する
title = ax.text(x, y, "title t = {}".format(t))

配列に格納

  • 上で作成した画像とタイトルを配列に格納する.
images.append(image + image_2 + [title])

プロット

  • 適当な fig に入れます.
ani = ani.ArtistAnimation(fig, images, interval = 100)

その他設定

  • 凡例

凡例をセットするときは次のようにプロットしたグラフ順に配列を作成する.

ax.legend(["label 1", "label 2"])
  • 画像サイズ

次のように調整します.

fig.subplots_adjust(left = 0.2, right = 0.95, bottom = 0.15, top = 0.9)
  • 保存方法
  • GIFの場合は,writer = "pillow" で保存できる.
    dpi , fps はお好みで
ani.save("movie.gif", writer = "pillow", dpi = 300, fps = 30)
  • MP4の場合は writer = "ffmpeg" で保存できる.
    (別途 ffmpeg をダウンロードする必要あり)
ano.save("movie.mp4", writer = "ffmpeg")

メモリ,軸,ラベルの設定は通常のものが使用できます.

作成例

  • 作成したもの

時々刻々と変化するsin波とcos波を同時にプロット

  • コード
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as ani

#. -- Time parameter --
it_min = 0
it_max = 100
t_min = 0
t_max = 1
dt = t_max/it_max


#. -- Coordinate --
x_min = 0
x_max = 10
dx = 0.1
x = np.arange(x_min, x_max, dx)


#. -- Graph Setting --
fig, ax = plt.subplots(figsize = (6, 6))
images = []


#.  -- Time loop --
for it in range(it_min, it_max) :
    
    #. function
    t = dt*it
    y = np.sin(x - t)
    y2 = np.cos(x - t)
    
    #. plot 
    image_1 = ax.plot(x, y, color = "steelblue")
    image_2 = ax.plot(x, y2, color = "orangered")
    title = ax.text(4, 1.20, "t = {:.1f}".format(t), fontsize = 16)
    images.append(image_1 + image_2 + [title])

#. Setting
ax.legend(["sin", "cos"], loc = "upper right")
fig.subplots_adjust(left = 0.1, right = 0.95, bottom = 0.1, top = 0.9)

#. Save
ani = ani.ArtistAnimation(fig, images, interval = 1000)
ani.save("sin_cos.gif", writer = "pillow", fps = 30)
#ani.save("sin_cos.mp4", writer = "ffmpeg", fps = 30, dpi = 300)
  • 実行結果
    sin_cos.gif

不具合?なのかわからないのですがGIFをクリックするとスムーズに再生されます.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0