LoginSignup
16
16

More than 5 years have passed since last update.

pyplotで日本語表記するための設定(何周目?)

Last updated at Posted at 2018-03-14

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()

matplotlib.png

おめでとう、オレ。

終わりに

ここまでたどり着くまでに、いろんな人のblogやらqiitaへのポストやらを参考にさせていただきました。
コピペしすぎて、出典が分からなくなってしまいました。全てのMatplotlibネタを書かれた人に謝罪と感謝を。
すみませんでした、そして、ありがとうございました。

16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16