LoginSignup
74
65

More than 1 year has passed since last update.

【Python】matplotlibを日本語化する

Last updated at Posted at 2018-08-19

matplotlibで日本語を使おうとすると、デフォルトのままでは文字化けしてしまいます。
そこで文字化けしないようにするための設定を紹介します。

お困りごと

Jupyter Notebook上で以下のような処理を実行したときに
グラフのラベルが上手く表示されない。

from numpy.random import *
from matplotlib import pyplot as plt
%matplotlib inline

# 乱数生成
rand_nums = randn(100)

# ヒストグラム表示
plt.hist(rand_nums)
plt.xlabel("X軸と表示したい")
plt.ylabel("Y軸と表示したい")

実行結果
hist_miss.png

環境

MacOS、Python 3.6(Anaconda)、Jupyter Notebookがインストールされている環境。

準備

以下のサイトからIPAexGothicフォントをダウンロードし、matplotlibで使えるようにします。
https://ipafont.ipa.go.jp/node17

※ 2022/06/14追記 リンクが切れていました。以下からダウンロードできそうです。
https://moji.or.jp/ipafont/ipafontdownload/

※以下参考までにコマンドを書いてますが、Finder等使ってもらっても可です。
※また、フォントはこの記事の執筆時の最新であるipaexg00301で動かしていますが、ipaexg00401など、他のバージョンでも大差ないと思います。

  1. ipaexg00301.zipをダウンロードする。

  2. ダウンロードしたzipファイルを展開し、中にあるipaexg.ttfを
    ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
    へ配置する。

unzip ~/Downloads/ipaexg00301.zip
mv ~/Downloads/ipaexg00301/ipaexg.ttf ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
  1. ~/.matplotlib内のfontList.py3k.cacheを削除する。
    (また、ここでJupyterを起動している場合は再起動する。)
rm -f ~/.matplotlib/fontList.py3k.cache 

方法① 実行時に設定する

先程の処理に一行追加する。

from numpy.random import *
from matplotlib import pyplot as plt
%matplotlib inline

# 乱数生成
rand_nums = randn(100)

# 追加部分 フォントを指定する。
plt.rcParams["font.family"] = "IPAexGothic"

# ヒストグラム表示
plt.hist(rand_nums)
plt.xlabel("X軸と表示したい")
plt.ylabel("Y軸と表示したい")

実行結果
hist_miss.png

ただ、こちらの場合はファイルを作成する度に記述する必要があるので、
次に紹介する方法の方が汎用的だと思います。

方法② 設定ファイルを修正する

~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrcの記述を修正します。

vi ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc

196行目辺りにfont.familyの記述があるので
以下のようにsans-serifの行をコメントアウトし、IPAexGothicの行を追加する。

#font.family         : sans-serif
font.family         : IPAexGothic

Jupyterを再起動し、冒頭の処理を実行する。

実行結果
hist_miss.png

まとめ

日本語を使う可能性があるのであれば、とりあえず②の方法で日本語化しておくと良いのではないでしょうか。

74
65
1

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
74
65