matplotlibでpyplotする時の日本語を表示するためのフォント設定のハナシ。
一度設定すると忘れてしまうので、別の環境を設定する時にどうしたら良いか分かんなくなってしまうので、メモ。
matplotlibrc の在り処
matplotlibで使うフォントの設定は、matplotlibrcに設定する必要がある。
import matplotlib
print(matplotlib.matplotlib_fname())
macOSとWindowsの場合は、$HOME/.matplotlib/matplotlibrc
だった。Ubuntuは、$HOME/.config/matplotlib/matplotlibrc
だった。
フォントの名前を知る
Windowsだと拡張子が.ttc
になっているTrueType Collectionファイルは指定できないし、Macだと「ヒラギノ角ゴシック」のような日本語のフォント名になっているものを、どうやってmatplotlibrcファイルに指定したら良いか分からないので、ソレを知るために、font_manager
からフォント名を取得する。
import matplotlib.font_manager as fm
import pandas as pd
fonts = fm.findSystemFonts()
tmp = []
for f in fonts:
font = fm.FontProperties(fname=f)
fname = font.get_name()
tmp.append((f, fname))
df = pd.DataFrame(tmp, columns=['path', 'name'])
するとdf
に、フォントのファイル名とフォント名が格納されるので、フォントのファイル名からフォント名を探す。
例えば、Rictyフォントはどうなってるの?という場合は、次のようにする。
print(df[df['path'].apply(lambda s: 'Ricty' in s)])
これで、使いたいRictyフォントがそのまんまRicty
だと分かった。
font.familyの内容の変更
site-packages/matplotlib/mpl-data/matplotlibrcファイルの中身を見ると、199行目には次のように書いてある。
# font.family : sans-serif
つまり、デフォルトのfont.familyはsans-serifである、と。
そして、211行目は次のようになっている。
# font.sans-serif : DejaVu Sans, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
ということは、自分のmatplotlibrc
は、このfonts.sans-serif
をoverrideするようにすればいい。
font.sans-serif: Ricty, sans-serif
pyplot()で日本語を設定する
ここまできたら、後はpyplot()に日本語ラベルを設定するだけだ。
import matplotlib.pyplot as plt
import numpy as np
plt.gca().set_aspect('equal', adjustable='box')
plt.scatter(np.random.rand(100)*10, np.random.rand(100)*10, label='青')
plt.scatter(np.random.rand(100)*10, np.random.rand(100)*10, label='橙')
plt.plot(np.random.rand(10)*10, label='青線')
plt.plot(np.random.rand(10)*10, label='橙線')
plt.title('日本語タイトル')
plt.xlim([0, 10]), plt.ylim([0, 10])
plt.xlabel('X軸'),plt.ylabel('Y軸')
plt.legend(loc=0)
plt.show()
おめでとう、オレ。
終わりに
ここまでたどり着くまでに、いろんな人のblogやらqiitaへのポストやらを参考にさせていただきました。
コピペしすぎて、出典が分からなくなってしまいました。全てのMatplotlibネタを書かれた人に謝罪と感謝を。
すみませんでした、そして、ありがとうございました。