plotlyは,Pythonでインタラクティブ・プロットを簡単に作れるライブラリの一つ。以下は折れ線グラフの作り方の説明。
まずは基本モジュール読み込み。
import pandas as pd
import datetime
import warnings
warnings.filterwarnings('ignore')
jupyter notebookでplotlyの出力をファイル保存すると,plotlyのグラフがjupyter上に表示されなくなることがある。そのときは以下を実行する。
from plotly.offline import init_notebook_mode
init_notebook_mode(connected = True)
データはAltairと同様に,以下のデータサンプルのようなlong formatにする。
from vega_datasets import data
source = data.stocks()
display(source.head())
たった数行(実質1行)で出来上がり。
すばらしい。
情報源
import plotly.express as px
fig = px.line(source, x="date", y="price",
color="symbol", title='stock price chart')
fig.show()
# fig.write_html("plotly.html") # htmlファイルにしたいとき
グラフサイズはブラウザの横幅に応じて自動で調整されるが,以下のように決め打ち(fig.update_layout()
)も出来る。
また,マウスオーバで表示されるテキスト枠のタイトルも設定(hover_name
)できる。
fig = px.line(source, x="date", y="price",
color="symbol", title='stock price chart', hover_name="symbol")
fig.update_layout(
autosize=False,
width=600,
height=400)
fig.show()
# fig.write_html("plotly2.html") # htmlファイルにしたいとき