亀の歩み

備忘録として

matplotlibで、箱ひげ図と日本語の使い方

matplotlibを使うとお手軽に箱ひげ図が書けるようです。

リファレンス:pyplot — Matplotlib 1.5.0 documentation
例:http://matplotlib.org/examples/pylab_examples/boxplot_demo.html

#coding: utf-8

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

fp = FontProperties(fname=r'C:\WINDOWS\Fonts\YuGothic.ttf', size=14)
#日本語表示用のフォント

data = [0.09, 0.10, 0.12, 0.04, 0.06, 0.14, 0.13, 0.28 ,0.29, 0.17]
data = [data[:], data[:]] #リストのコピーにはスライス
del data[1][7:9] #2つ目のデータから外れ値を削除

label = (u'なんとか', u'かんとか') #x軸のラベル
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid() #グリッド線
bp = ax.boxplot(data) #箱ひげ図を描画
ax.set_xticklabels(label, fontproperties=fp)
plt.ylim(0,0.3)
plt.show()

f:id:shinep:20160110052900p:plain

私が使いそうだと思ったboxplotのオプションを書いておきます。

  • sym:外れ値のマーカー

 'gD'(ひし形)、'rs'(正方形)、'o'(丸)

  • vert:バーの縦横

 True(縦)、False(横)

  • whis:ひげの長さ

 デフォルトは1.5、'range'で外れ値がなくなります。


matplotlibで日本語を使うには、fontproperties(凡例はprop)で和文フォント指定する必要があるようです。

Python - matplotlibで日本語 - Qiita

from matplotlib.font_manager import FontProperties
fp = FontProperties(fname=r'C:\WINDOWS\Fonts\YuGothic.ttf', size=14)
#使いたいフォントファイルを指定

が必要になります。

文字列の前にuをつけてUnicodeオブジェクトにしないと、エラーが出るみたいですね。