boxplot

与えられたデータの箱ひげ図を描く。

デフォルトでは,第1と第3の四分位(25と75パーセンタイル)を箱の上端と下端に,中央値を箱の中の横線に,第1と第3の四分位から両者の間の幅(Q3-Q1)の1.5倍さらに加えた値を髭に,その二つの髭からはずれた値を外れ値として〇で描く。したがって,箱に入る範囲には元データの半数の値が含まれる。

データのパーセンタイル値を髭の値とすることもできる。たとえば,whis=(5, 95)を与えると,5パーセンタイルと95パーセンタイルが髭の値として描かれる。

外れ値を示さないようにするには,showfliers=Noneを与える。

一つの図のパネルに複数の箱髭を描くには,numpy の二次元配列にするか,複数の一次元データをリストに格納する。データの中に欠損値は許容されない(欠損値があると箱髭が描かれない)ので,箱髭を描くデータの個数が異なる場合にはリストを使う。

正規分布について,scipy.stats.normを用いて箱と髭の位置そして,髭の範囲に含まれるデータの割合を求めてみよう。q1= norm.ppf(0.25)=-0.674, q3=norm.ppf(0.75)=0.674である。さらに,qu=q3+(q3-q1)*1.5; qd=q1-(q3-q1)*1.5の髭の間に含まれるデータの割合はstats.norm.cdf(qu)-stats.norm.cdf(qd)=0.9930となることから99.3%である。したがって,正規分布するデータなら髭の間に99.3%のデータが含まれる。

This function draw a box plot for the provided data. 

By default, the box plot is constructed with the first and third quartiles (25th and 75th percentiles) as the ends of the box, the median as a horizontal line inside the box, and the values extended from the first and third quartiles by 1.5 times the interquartile range (Q3-Q1) as the whiskers. Outliers, values that are beyond the whiskers, are depicted as circles. Therefore, the box encompasses half of the original data values. To draw multiple box plots in one panel, you can use a 2D array in NumPy or store multiple 1D data in a list. Note that missing values are not allowed (if there are any missing values, the box plot will not be drawn), so when dealing with different numbers of data points for the box plot, it is advisable to use a list. Let's consider a normal distribution and use scipy.stats.norm to determine the positions of the box and whiskers, as well as the proportion of data within the whiskers' range. For a normal distribution, q1 = norm.ppf(0.25) = -0.674 and q3 = norm.ppf(0.75) = 0.674. Furthermore, qu = q3 + (q3 - q1) * 1.5; qd = q1 - (q3 - q1) * 1.5, and the proportion of data within the whiskers' range is given by stats.norm.cdf(qu) - stats.norm.cdf(qd) = 0.9930, indicating 99.3%. Hence, if the data follows a normal distribution, 99.3% of the data will fall within the whiskers' range. 

# test script of boxplot 

from matplotlib import pyplot as plt

import numpy as np

from scipy.stats import norm


data=[np.random.randn(100000),np.random.randn(10000)]


plt.ion()

plt.clf()

plt.subplot(1,2,1)

plt.boxplot(data)

q1=norm.ppf(0.25)

q3=norm.ppf(0.75)

plt.plot([0,3],[q1,q1])

plt.plot([0,3],[q3,q3])

qd=q1-(q3-q1)*1.5

qu=q3+(q3-q1)*1.5

plt.plot([0,3],[qu,qu])

plt.plot([0,3],[qd,qd])


portion_theory=norm.cdf(qu)-norm.cdf(qd)

portion_obs=np.sum((qd<data[0]) & (data[0]<qu))/len(data[0])

print(portion_theory,portion_obs)


plt.subplot(1,2,2)

plt.boxplot(data[0],whis=(5,95),showfliers=False)

p05=np.percentile(data[0], 5)

p95=np.percentile(data[0],95)

plt.plot([0,2,np.nan,0,2],[p05,p05,np.nan,p95,p95])