LoginSignup
6
7

More than 5 years have passed since last update.

JupyterNotebookで、アニメーションするグラフを簡単に作る(plotly)

Posted at

jupyter.gif

目的

  • JupyterNotebook上で、グラフをアニメーションさせたい。
  • 面倒くさいインターフェースはいやだ。簡単に試したい。

想定されるシチュエーション

  • 損失関数の推移
  • 最適化の経緯
  • 発表とか勉強会用に、理解しやすいように使うのが主かもしれません。

コード全量

結論

# import plotly as offline mode
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()

from sklearn.datasets import load_iris
import pandas as pd
import numpy as np


frames = []
xaxis = []

# framesに突っ込んだデータの通りに、勝手にアニメーションしてくれる。
# 今回は y = x **2のグラフを想定している。
for x in np.arange(-10,11,1):
    xaxis.append(x)
    data = [
        go.Scatter(
            x = xaxis,
            y = np.array(xaxis) ** 2
        )
    ]
    frames.append({"data": data})

layout = go.Layout(
    title="アニメーション サンプル",
    xaxis={"title":"x", "range": [-10, 10]},
    yaxis={"title":"y(x ** 2)", "range":  [-100, 100]},
    showlegend=True,
    height=600,
    updatemenus=[{'type': 'buttons',
                     'buttons': [{'label': '再生',
                                  'method': 'animate',
                                  'args': [None]}]}]
)

fig = go.Figure(
    data=data,
    layout=layout,
    frames=frames
)
offline.iplot(fig)

このように表示されます

jupyter.gif

6
7
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
6
7