LoginSignup
13

More than 5 years have passed since last update.

seaborn日本語表示設定

Last updated at Posted at 2018-03-18

目的

Pythonで使うseabornのチャートを日本語表示できるようにする。

実行環境

実行環境は以下の通り。

Python version 3.5.3 |Anaconda custom (64-bit)| (default, May 15 2017, 10:43:23) [MSC v.1900 64 bit (AMD64)]
Pandas version 0.20.1
Matplotlib version 2.0.2
Seaborn version 0.7.1

現状の課題

matplotlibでは既定フォントがDejaVu Serifになっており、日本語を表示しようとしても文字化けしてしまう。また、多くの日本語フォント(.ttc)に対応していない。

解決方法

1. 使用可能なフォント一覧を表示

以下のコードを実行し、現在使用可能なフォント一覧を表示する。

import matplotlib.font_manager
print([f.name for f in matplotlib.font_manager.fontManager.ttflist])

実行結果は下記の通り。この中に日本語対応フォントがあればそれを使用する。自分の場合はなかったため、新たにフォントを追加する必要がある。

['DejaVu Sans Mono', 'STIXSizeTwoSym', ..., 'Berlin Sans FB', 'Niagara Engraved']

2. 日本語フォントのダウンロード

matplotlibで使用可能な日本語フォントをダウンロードする。
matplotlibでは.ttf, .otfファイルをサポートしている。使用可能なフォントは下記のとおり。

ダウンロードしzipファイルを解凍後、インストールする。

3. matplotlib設定変更

フォントをインストールしただけではmatplotlibのデフォルトフォントとして使用できないため、matplotlib設定ファイルを書き換え、デフォルトのフォントを変更する。
matplotlib設定ファイルの場所は次のコードで確認できる。

import matplotlib
print(matplotlib.matplotlib_fname())

実行結果

C:\Users\Username\Anaconda3\lib\site-packages\matplotlib\mpl-data\matplotlibrc

~mpl-data\matplotlibrc をテキストエディタで開き、以下の部分を変更する。
デフォルトではDejaVu Sansになっている。

#font.sans-serif     : DejaVu Sans, 

変更後

#font.sans-serif     : IPAPGothic, DejaVu Sans, 

4. seaborn設定変更

次に、C:\Users\Username\Anaconda3\Lib\site-packages\seaborn\rcmod.pyをテキストエディタで開き、以下の部分を変更する。

83行目付近

def set(context="notebook", style="darkgrid", palette="deep",
        font="IPAPGothic", font_scale=1, color_codes=False, rc=None):

193行目付近

"font.family": ["IPAPGothic"],

194行目付近

"font.sans-serif": ["Arial", "Liberation Sans","Bitstream Vera Sans", "IPAPGothic"],

cache削除

matplotlibはC:\Users\Username\.matplotlib\fontList.py3k.cacheを参照するため、~mpl-data\matplotlibrcを変更しただけではフォントは変更されない。

matplotlibをimportする前に、.matplotlib\fontList.py3k.cacheを削除する。

結果

seabornで描画したグラフが日本語表示される。

課題

  • matplotlib, seabornをアップデートするたびに設定し直さなければならない。

参考にしたリンク

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
13