【Python】matplotlib3.2の日本語フォント設定方法【公式遵守】


はじめに

  • matplotlib (https://matplotlib.org/) はPythonでグラフなどを描画するための有名なライブラリです
  • ただし、グラフ内のラベルなどで日本語を使いたい場合、デフォルトだと文字化け(◻︎◻︎◻︎◻︎◻︎となるので豆腐と呼ばれているよう)が発生してしまいます
  • 自分が matplotlib 日本語 で調べた時に出てきた記事が結構力技の方法(インストールしたmatplotlibの中身を直接書き換えるようなやつ等)ばかりで困ったので、公式で紹介されている方法を書いておきます

日本語化ライブラリは使わないの?

font_manager.createFontList is deprecated. font_manager.FontManager.addfont is now available to register a font at a given path.

  • よって、matpotlibを3.2.0以上で使用している場合、次のような警告が表示されるようになりました
MatplotlibDeprecationWarning: 
The createFontList function was deprecated in Matplotlib 3.2 and will be removed two minor releases later. Use FontManager.addfont instead.
  • japanize-matplotlib のソースコードを読めば分かるように複雑なことはしていないので、今回は自前で同等の実装をFontManager.addfontに置き換えて行います

FontManager.addfont で日本語フォントを追加する

  • 日本語フォント(今回はIPAexゴシック)をダウンロード&解凍する
  • 使用するリポジトリにダウンロードした.ttfファイルを置く
    • 例えばfontsディレクトリを作って /fonts/ipag.ttf のように置く
  • fontManager.addfont で読み込むだけ
    • 自分はclassmethodだと思い込んで時間を無駄にした...
from matplotlib import font_manager

font_manager.fontManager.addfont("/fonts/ipag.ttf")
matplotlib.rc('font', family="IPAGothic")
  • フォントが複数がある場合は次のようにすればOK
from matplotlib import font_manager

font_files = font_manager.findSystemFonts(fontpaths=["/fonts"])

for font_file in font_files:
    font_manager.fontManager.addfont(font_file)

matplotlib.rc('font', family="IPAGothic")

おまけ

  • ちなみにバージョンが3.2未満の場合は次のように対応できます
    • japanize-matplotlib でやってることとほぼ同じ
from matplotlib import font_manager

font_files = font_manager.findSystemFonts(fontpaths=["/fonts"])
font_list = font_manager.createFontList(font_files) # 3.2以上の場合は警告が出る
font_manager.fontManager.ttflist.extend(font_list)
matplotlib.rc('font', family="IPAGothic")

終わりに

  • なにも大したことはしてないのですが他の人が調べた時に惑わされないように書き残します