matplotlibで日本語フォントを利用する
matplotlibはデフォルトの設定では日本語を表示できなので,日本語フォントを設定して表示できるようにしよう.
現在使用しているフォントを確認
code: python
import matplotlib
matplotlib.rcParams.get('font.family') # => 'san-serif' 設定ファイルを設置
matplotlibrcのパスと設定ディレクトリの場所を確認
code: python
matplotlib.matplotlib_fname()
# => '/home/altescy/.pyenv/versions/anaconda3-5.2.0/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc'
matplotlib.get_configdir()
# => '/home/altescy/.config/matplotlib'
matplotrcを設定ディレクトリにコピー
$ cp /home/altescy/.pyenv/versions/anaconda3-5.2.0/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc /home/altescy/.config/matplotlib/
設定を変更
先ほどコピーしたmatplotlibrcを以下のように変更.フォントはお好みのものを選んでね.
code: ~.config/matplotlib/matplotlibrc
# font.family: san-serif
font.family: TakaoPGothic
ちなみに利用可能なフォントは以下で見られる:
code: python
import matplotlib.font_manager as fm
fm.findSystemFonts()
変更が反映されない場合
キャッシュが残っていて変更が反映されない場合がある.
~/.cache/matplotlib以下にあると思われるfontList.cacheとfontList.py3k.cacheを削除.
$ rm ~/.cache/matplotlib/fontList.cache ~/.cache/matplotlib/fontList.py3k.cache
これで日本語が使えるようになったかな?