LoginSignup
31
25

More than 5 years have passed since last update.

Jupyterでmatplotlibのjavascriptアニメーションを動かす

Posted at

Jupyter上でmatplotlibのグラフをアニメーションさせる際、nbaggバックエンド&animationモジュールを良く使うのですが、nbaggは環境やフレームレートによっては描画が結構カクつきます。
matplotlib 2.1で追加されたjavascript HTMLアニメーション
を試したところ、とても軽快で使い勝手も良かったのでメモしておきます。

動作環境

Windows10 64bit
Core i7-6700
Chrome 64.0.3282.119
python 3.6.3
jupyter 6.1.0
matplotlib 2.1.0

使い方

example.py
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np

t = np.linspace(0, 6*np.pi, num=60)
x = 2.0 * np.cos(t) + 5.0 * np.cos(2.0/3.0 * t)
y = 2.0 * np.sin(t) - 5.0 * np.sin(2.0/3.0 * t)

fig, ax = plt.subplots(figsize=(5, 5))
l, = ax.plot([-7, 7],[-7, 7])

animate = lambda i: l.set_data(x[:i], y[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t), interval = 1000/30.0)

from IPython.display import HTML
HTML(ani.to_jshtml())

smp.gif

動作デモ

重要なのは末尾の一行で、FuncAnimationオブジェクトの to_jshtml メソッドで生成したアニメーションのHTML要素を、IPython.display.HTMLでインライン表示しています。ArtistAnimationでも同様の手順で表示可能です。

アニメーションは静的なHTML要素として出力されるので↑の様にnbviewer上でも再生出来てしまいます。操作ボタン類も中々充実していて、再生速度の変更やコマ送り・コマ戻しも可能です。デバッグ時に便利そうですね。

パフォーマンス

上手い計測方法が思い浮かばなかったので、愚直にjavascript版とnbagg版でアニメーション再生中の平均CPU使用率を比べてみました。コードは上のデモと同じものを使っています。

再生前 javascript nbagg
(1.2%) 3.0% 34%

javascript版の軽さが際立ってます。

参考リンク

Jupyter上でmatplotlibのアニメーションを再生する - Qiita
https://qiita.com/Tatejimaru137/items/6083e2e3a4e618da6274

Inline animations in Jupyter - Stack Overflow
https://stackoverflow.com/questions/43445103/inline-animations-in-jupyter/43447370

31
25
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
31
25