techno_memo

個人用の技術メモ。python・ROS・AI系のソフトウェア・ツールなどの情報を記載

plotlyによるグラフ描画

概要

 pythonのライブラリ plotlyを用いて数値データをグラフ描画する。

plotly

plotlyはブラウザでインタラクティブに操作可能なグラフを生成することができる。 本記事では基本的な使い方と設定方法についてまとめる。

基本的なグラフの描画

plotlyのインストールは下記pipコマンドで行う。

pip install plotly

基本的なグラフの描画方法は公式チュートリアルの下記ページにまとめてある。

[https://plotly.com/python/line-charts/:embed:cite]

上記にはplotly expressという高レベルapiによる描画方法と従来のplotlyの描画方法(Graph objects)による方法が記述されている。 それぞれの方法でy=x2の線・散布図・棒グラフを下記のように記述することができる。

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

x = np.arange(10)

#plotly expressによる描画
df = pd.DataFrame({ 'x_axis_label' : x,
                    'y_axis_label' : x**2})
fig = px.line(df, x="x_axis_label", y="y_axis_label", title='plot test') #散布図
#fig = px.scatter(df, x="x_axis_label", y="y_axis_label", title='plot test') #散布図
#fig = px.bar(df, x="x_axis_label", y="y_axis_label", title='plot test') #棒グラフ

#graph objectによる描画
#fig = go.Figure(data=go.Scatter(x=x, y=x**2, mode="lines"))  #線グラフ
#fig = go.Figure(data=go.Scatter(x=x, y=x**2, mode="markers"))  #散布図
#fig = go.Figure(data=go.Bar(x=x, y=x**2))  #棒グラフ


#描画設定

fig.update_layout(
    title_text='plot test',
    title_x=0.5,    #グラフタイトルを中央に寄せる
    xaxis_title_text='x axis label',    #x軸ラベル
    yaxis_title_text='y axis label',    #y軸ラベル
    title_font_size=30,                 #タイトルフォントサイズ
    title_font_family='Times New Roman',    #タイトルフォント
    title_font_color='red'  #タイトル色
)
fig.show()

f:id:sd08419ttic:20211024160328p:plain

plotly expressで描画する場合はpandas data frameを引数として指定する必要があるため、numpyのデータをpandasに変換する処理が必要となる。 また、タイトル名・軸名等は引数として設定することができる。graph objectの描画ではnumpyのデータを引数として指定する。グラフタイトルなどの設定はupdate_layoutによって設定する。

複数のグラフの描画

同じ軸設定で複数のグラフを表示する場合は下記のように実装できる。

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

x = np.arange(10)

#plotly expressによる描画
# df = pd.DataFrame({ 'x_axis_label' : x,
#                     'y_data' : x**2,
#                     'y_data2' : x**2 -2.0,
#                     'y_data3' : x**2 * 0.5,})
#fig = px.line(df, x="x_axis_label", y=["y_data","y_data2","y_data3"], title='plot test') #線グラフ
#graph objectによる描画
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=x**2, mode="lines"))
fig.add_trace(go.Scatter(x=x, y=x**2-2.0, mode="lines"))
fig.add_trace(go.Scatter(x=x, y=x**2 * 0.5, mode="lines"))

#描画設定
fig.update_layout(
    title_text='plot test',
    title_x=0.5,    #グラフタイトルを中央に寄せる
    xaxis_title_text='x axis label',    #x軸ラベル
    yaxis_title_text='y axis label',    #y軸ラベル
    title_font_size=30,                 #タイトルフォントサイズ
    title_font_family='Times New Roman',    #タイトルフォント
    title_font_color='red'  #タイトル色
)
fig.show()

f:id:sd08419ttic:20211024163906p:plain

plotly expressでは描画したいデータのy軸を含むcolumn名を指定すれば良い。 graph objectでは描画したいデータをfig.add_traceで追加する。

異なる種類のグラフを同じ画面で描画することもできる。

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

x = np.arange(10)

#plotly expressによる描画
df = pd.DataFrame({ 'x_axis_label' : x,
                     'y_data' : x**2,
                     'y_data2' : x**2 -2.0,
                     'y_data3' : x**2 * 0.5,})
fig = px.line(df, x="x_axis_label", y=["y_data"], title='plot test') #線グラフ
fig2 = px.scatter(df, x="x_axis_label", y=["y_data2"],color_discrete_sequence=["red"]) #線グラフ
fig3 = px.bar(df, x="x_axis_label", y=["y_data3"],color_discrete_sequence=["green"]) #線グラフ
fig.add_trace(fig2.data[0])
fig.add_trace(fig3.data[0])

#graph objectによる描画
#fig = go.Figure()
#fig.add_trace(go.Scatter(x=x, y=x**2, mode="lines"))
#fig.add_trace(go.Scatter(x=x, y=x**2-2.0, mode="lines"))
#fig.add_trace(go.Scatter(x=x, y=x**2 * 0.5, mode="lines"))

#描画設定
fig.update_layout(
    title_text='plot test',
    title_x=0.5,    #グラフタイトルを中央に寄せる
    xaxis_title_text='x axis label',    #x軸ラベル
    yaxis_title_text='y axis label',    #y軸ラベル
    title_font_size=30,                 #タイトルフォントサイズ
    title_font_family='Times New Roman',    #タイトルフォント
    title_font_color='red'  #タイトル色
)
fig.show()

f:id:sd08419ttic:20211029005108p:plain

plotly express で各グラフの色を変えるためにはcolor_discrete_sequenceオプションを使うことに注意する。

グラフの保存

描画したグラフはhtmlや画像(png/jpeg等)で保存することができる。 保存する場合は下記関数を呼び出す。

fig.write_html("path/to/file.html")
fig.write_image("ファイル名(パス含む).拡張子")

htmlの保存時に必要なライブラリがエラーが発生する場合がある。警告に従って下記コマンドで必要なライブラリをインストールして解消できる。

pip3 install kaleido

参考記事

plotly.com