hidekatsu-izuno 日々の記録

プログラミング、経済政策など伊津野英克が興味あることについて適当に語ります(旧サイト:A.R.N [日記])

Python plotly メモ

matplotlib とか seabone とかを使っていたのだけど、日本語表示の問題などどうにも使い勝手が悪いので、いろいろ探していたら plotly がすごく使いやすかったので今回はそのメモ。JavaScript などマルチプラットフォームで使えるので、今後はこっちに統一していきたい。

インストール

pip install plotly # こちらはグラフ描画の基盤的な機能
pip install plotly-express # 高レベルI/F

ライブラリのロード

import plotly.graph_objects as go
import plotly.express as px

グラフの描画

以下、data は pandas の DataFrame であるものとする。

ヒストグラム

fig = px.histogram(data, x="x") # 分割数を変えたい場合は nbins=50 などとする
fig.show()

散布図

fig = px.scatter(data, x="x", y="y")
fig.show()

直線

fig = px.line(data, x="x", y="y")
fig.show()

グラフの合成

fig1 = px.scatter(data, x="x", y="y")
fig2 = px.line(data, x="x2", y="y2", color_discrete_sequence=["red"]) # 色を変える
fig3 = go.Figure(data=fig1.data + fig2.data)
fig3.show()

軸情報の変更

fig3.update_xaxes(range=[最小, 最大], title_text='X軸')
fig3.update_yaxes(range=[最小, 最大], title_text='Y軸')

描画領域の変更

fig3.update_layout(
    margin=dict(l=20, r=20, t=20, b=20), # マージン
    width=500, # 幅
    height=300, # 高さ
    showlegend=False, # 凡例の表示
    title_text="タイトル", # タイトル
)