[matplotlib 3D] 26. ArtistAnimationで3D wireframe plotをアニメーションで表示

matplotlib 3D

はじめに

matplotlib mplot3dの3D wireframe plotをArtistAnimationを使って、アニメーションで表示する方法について解説する。

コード(matplotlib example)

Rotating 3D wireframe plot — Matplotlib 3.4.0 documentation

上記ページのコードをjupyter notebookで実行した結果、

%matplotlib nbagg
Warning: Cannot change to a different GUI toolkit: nbagg. Using notebook instead.

とのことでアニメーションが表示されなかった。

%matplotlib notebook

としてもアニメーションが表示されず、下の画像が表示された。

そこで、ArtistAnimationを使って書き改めた。

コード&解説

モジュールのインポート

バージョン

データ生成関数

Zデータを生成する関数generateを以下のように定義する。

X, Y meshgridの作成

X,Yデータをnp.meshgridで作成する。

plot_wireframeでプロット

関数generateのphiを0とした時のデータをplot_wireframeで表示すると以下のようになる。

アニメーション用グラフの作成

imsで空のリストを作成する。
phiの0個目から50個目まで順次 Zのdataを作成して、wireframeでプロット(im)を作成し、
imsにimをappendで追加していく。
ここで[im]と[]で囲むのがポイントとなる。
最終的にimsはplot_wireframeのリストとなる。

アニメーションの表示

ArtistAnimationでアニメーションを作成する。
figはアニメーションを表示するfigであり、imsはグラフのリストである。interval では図の表示時間[ms]を設定する。
アニメーションをIPythonの HTML displayで表示する。to_html5_videoでアニメーションをHTML5 に変換できる。

表示されるアニメーションは以下のようになる。

コードをダウンロード(.pyファイル)

コードをダウンロード(.ipynbファイル)

参考

https://matplotlib.org/api/_as_gen/matplotlib.animation.ArtistAnimation.html
http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-as-interactive-javascript-widgets/

コメント