matplotlib.tickerで目盛りの数字を3桁カンマ区切りにする

matplotlibでグラフを作成するときに、目盛りの数字を3桁カンマ区切りにする方法をざっと探したけどあまりピンとくるものがなかったので書き留めたいと思います。

個人のブログですので内容に誤りがある場合があります。きちんとした情報が必要なときはきちんと公式ドキュメントを読んでください。

結論

matplotlib.tickerを使います。

matplotlib.org

tickerは軸の場所やフォーマットを操作するのに使うものらしいです。

このコードを記載すると3桁カンマ区切りができます。

plt.gca().get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda v,p: f'{int(v):,d}'))
plt.gca().get_xaxis().set_major_formatter(ticker.FuncFormatter(lambda v,p: f'{int(v):,d}'))

例えばこんな感じ

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df_1 = pd.DataFrame({'A':['a', 'b', 'c', 'd'],
                     'B':[10000000,20000000,30000000,40000000]})

plt.bar(df_1['A'],df_1['B'])
plt.gca().get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda v,p: f'{int(v):,d}'))