44
40

More than 5 years have passed since last update.

JupyterLab上でmatplotlibのアニメーションを出力する

Posted at

JupyterLabを使っているとmatplotlibで作成したアニメーションをnotebook上で再生できず困っていたのですが、
解決方法が分かったので共有します。

環境

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.13.6
BuildVersion:   17G65
$ python -V
Python 3.6.8 :: Anaconda, Inc.
$ jupyter lab --version
0.35.3
$ python -c "import matplotlib; print(matplotlib.__version__)"
3.0.0

解決方法

方法1: IPython.display.HTMLを使う

後の方法2よりもこちらのほうが簡単で良いと思います。

以下は確認用のコードです。jupyter labを起動させて下のコードを貼り付けてアニメーションが表示されるか試すことができます。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2 * np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2 * np.pi, 128),
                    init_func=init, blit=True, interval=50)

HTML(ani.to_jshtml())
# HTML(ani.to_html5_video())  # またはこちら

出力結果:

sin_animation.gif

to_jshtml()によりアニメーションをHTML表現に変換したものをHTML()で表示させています。ボタンによるインタラクティブな操作ができていい感じです。
to_html5_video()でHTML5 video tagを作成することもできます。

方法2: jupyter-matplotlibを使う

参考までに、別の方法も載せておきます。

jupyter-matplotlibをインストールし、%matplotlib widgetのmagic commandを実行することでも解決できました。
自分がインストールしたバージョンはv0.3.0です。

実行したコマンド:

conda install -c conda-forge ipympl
# conda install nodejs  # 必要なら
jupyter labextension install @jupyter-widgets/jupyterlab-manager
jupyter labextension install jupyter-matplotlib

コード:

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

%matplotlib widget

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2 * np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2 * np.pi, 128),
                    init_func=init, blit=True, interval=50)

notebookに以下のようなアニメーションが出力されていれば成功です。

anim.gif

補足

作成したアニメーションを保存するときは、例えばこんな感じで。下のコードを実行するには事前にimagemagickをインストールしておく必要があります。

ani.save('anim.gif', writer='imagemagick', fps=10)

参考

44
40
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
44
40