v-crn Code Log

主に備忘録

IPython上でGIFを表示する

前提

ルートディレクトリに表示したいGIFファイルがある場合を想定します。

!ls
sample_data  sin_curve.gif

ちなみに上の「sin_curve.gif」を生成するコードはこんな感じ。

%%
!pip install animatplot

%%
"""
Introduction to animatplot
https://animatplot.readthedocs.io/en/latest/tutorial/getting_started..html#Basic-Animation
"""

import numpy as np
from matplotlib import pyplot as plt
import animatplot as amp


def main():
    xs = np.linspace(0, 1, 50)
    ts = np.linspace(0, 1, 20)
    Xs = np.asarray([xs] * len(ts))
    Ys = [np.sin(2 * np.pi * (xs + t)) for t in ts]
    """
    # you can also write
    Xs, Ts = np.meshgrid(xs, ts)
    Ys = np.sin(2 * np.pi * (Xs + Ts))
    """
    block = amp.blocks.Line(Xs, Ys)
    anim = amp.Animation([block])
    anim.save_gif("sin_curve")
    plt.show()


if __name__ == '__main__':
    main()

GIFを表示するコード

以下のコードでGIFを表示させることができる。

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython import display
from pathlib import Path

gifPath = Path("sin_curve.gif")

with open(gifPath,'rb') as f:
  display.Image(data=f.read(), format='png')

Path("")の引数に対象のGIFファイルのPathを入れてれればおけまる。

参考

elegant way to display gif file in notebook? · Issue #10045 · ipython/ipython