はじめに
matplotlibのboxplotでは箱ひげ図を作成することができる。ヒストグラムは1種のデータの分布を調べるのに有用ではあるが、複数種のデータを比較するのには向いていない。一方、箱ひげ図は、コンパクトであるため複数種のデータを比較するのに向いている。ここでは、matplotlibの箱ひげ図であるboxplotの詳細な設定方法について説明する。
コード&解説
基本的な箱ひげ図

データの生成
np.random.randint(1,100,50)
で1から99のいずれかを要素としてもつ、要素数50個の配列を作成する。np.ones(25) * 50
で50を要素として持つ25個の配列を作成する。
同様に、flier_highは101〜199、flier_lowは-99〜-1を要素として持つ配列となる。np.concatenate
により、これらの配列を結合し、ひとつにする。
箱ひげ図の表示
ax1.boxplot(data)
で箱ひげ図を表示できる。
boxの中央値部分に切り込みを入れる

notch=True
で箱に中央値部分に切り込みを入れることができる。
外れ値のマーカーの設定

辞書形式でflierprops
を設定することで外れ値の見た目の調整ができる。
外れ値を非表示にする
showfliersによる設定

showfliers=False
で外れ値を非表示にできる。
symによる設定

sym=""
でも外れ値を非表示にできる。
boxを横にする

vert=False
で箱を横向きにすることができる。
ひげの調整
ひげを短くする

whis=1
で箱1個分離れた値までひげが伸びる。デフォルトは1.5なので、ひげが短くなる。
ひげを長くする

whis=2
で箱2個分離れた値までひげが伸びるので、ひげが伸びる。
ひげをパーセンタイルで指定

whis=[5,95]
のようにすることでひげの長さをパーセンタイルで指定することができる。
複数のboxplotを表示

data_ = [data,data2, data3]
のようにboxplotしたいデータをリストにして渡すことで複数のboxplotを表示できる。
boxplotの表示位置を変える

positions=[1,3,9]
のようにすることでboxplotを表示する位置を変えられる。
boxの幅を変える

widths=[.1,.3,.9]
のようにすることで各boxの幅を変えられる。
算術平均を表示

showmeans=True
で算術平均を表示できる。
中央値の線の設定

medianprops=medi_style
で辞書形式のmedi_styleを指定することで中央値の線の見た目を変えられる。
参考

コメント