十二、箱型圖

 

 

In [ ]:
'''
箱型圖

箱型圖:又稱爲盒須圖、盒式圖、盒狀圖或箱線圖,是一種用做顯示一組數據分散狀況資料的統計圖
包含一組數據的:最大值、最小值、中位數、上四分位數(Q3)、下四分位數(Q1)、異常值
① 中位數 → 一組數據平均分紅兩份,中間的數
② 上四分位數Q1 → 是將序列平均分紅四份,計算(n+1)/4與(n-1)/4兩種,通常使用(n+1)/4
③ 下四分位數Q3 → 是將序列平均分紅四份,計算(1+n)/4*3=6.75
④ 內限 → T形的盒須就是內限,最大值區間Q3+1.5IQR,最小值區間Q1-1.5IQR (IQR=Q3-Q1)
⑤ 外限 → T形的盒須就是內限,最大值區間Q3+3IQR,最小值區間Q1-3IQR (IQR=Q3-Q1)
⑥ 異常值 → 內限以外 - 中度異常,外限以外 - 極度異常

plt.plot.box(),plt.boxplot()
'''
In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
In [6]:
# plt.plot.box()繪製

fig,axes = plt.subplots(2,1,figsize=(10,6))
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
# 箱型圖着色
# boxes → 箱線
# whiskers → 分位數與error bar橫線之間豎線的顏色
# medians → 中位數線顏色
# caps → error bar橫線顏色

df.plot.box(ylim=[0,1.2],
           grid = True,
           color = color,
           ax = axes[0])
# color:樣式填充

# df.plot.box(vert=False, 
#             positions=[1, 4, 5, 6, 8],
#             ax = axes[1],
#             grid = True,
#            color = color)
# vert:是否垂直,默認True
# position:箱型圖佔位
Out[6]:
<matplotlib.axes._subplots.AxesSubplot at 0x1eba85398d0>
 
In [3]:
# plt.boxplot()繪製
# pltboxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, 
# usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, 
# labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_xticks=True, autorange=False, 
# zorder=None, hold=None, data=None)

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
plt.figure(figsize=(10,4))
# 建立圖表、數據

f = df.boxplot(sym = 'o',  # 異常點形狀,參考marker
               vert = True,  # 是否垂直
               whis = 1.5,  # IQR,默認1.5,也能夠設置區間好比[5,95],表明強制上下邊緣爲數據95%和5%位置
               patch_artist = True,  # 上下四分位框內是否填充,True爲填充
               meanline = False,showmeans=True,  # 是否有均值線及其形狀
               showbox = True,  # 是否顯示箱線
               showcaps = True,  # 是否顯示邊緣線
               showfliers = True,  # 是否顯示異常值
               notch = False,  # 中間箱體是否缺口
               return_type='dict'  # 返回類型爲字典
              ) 
plt.title('boxplot')
print(f)

for box in f['boxes']:
    box.set( color='b', linewidth=1)        # 箱體邊框顏色
    box.set( facecolor = 'b' ,alpha=0.5)    # 箱體內部填充顏色
for whisker in f['whiskers']:
    whisker.set(color='k', linewidth=0.5,linestyle='-')
for cap in f['caps']:
    cap.set(color='gray', linewidth=2)
for median in f['medians']:
    median.set(color='DarkBlue', linewidth=2)
for flier in f['fliers']:
    flier.set(marker='o', color='y', alpha=0.5)
# boxes, 箱線
# medians, 中位值的橫線,
# whiskers, 從box到error bar之間的豎線.
# fliers, 異常值
# caps, error bar橫線
# means, 均值的橫線,
 
{'whiskers': [<matplotlib.lines.Line2D object at 0x000001EBA8329550>, <matplotlib.lines.Line2D object at 0x000001EBA83296A0>, <matplotlib.lines.Line2D object at 0x000001EBA833C5F8>, <matplotlib.lines.Line2D object at 0x000001EBA833C748>, <matplotlib.lines.Line2D object at 0x000001EBA834C630>, <matplotlib.lines.Line2D object at 0x000001EBA834C780>, <matplotlib.lines.Line2D object at 0x000001EBA835E668>, <matplotlib.lines.Line2D object at 0x000001EBA835E7B8>, <matplotlib.lines.Line2D object at 0x000001EBA83706A0>, <matplotlib.lines.Line2D object at 0x000001EBA83707F0>], 'caps': [<matplotlib.lines.Line2D object at 0x000001EBA8329B38>, <matplotlib.lines.Line2D object at 0x000001EBA8329F60>, <matplotlib.lines.Line2D object at 0x000001EBA833CB70>, <matplotlib.lines.Line2D object at 0x000001EBA833CF98>, <matplotlib.lines.Line2D object at 0x000001EBA834CBA8>, <matplotlib.lines.Line2D object at 0x000001EBA834CFD0>, <matplotlib.lines.Line2D object at 0x000001EBA835EBE0>, <matplotlib.lines.Line2D object at 0x000001EBA8367048>, <matplotlib.lines.Line2D object at 0x000001EBA8370C18>, <matplotlib.lines.Line2D object at 0x000001EBA8379080>], 'boxes': [<matplotlib.patches.PathPatch object at 0x000001EBA83292E8>, <matplotlib.patches.PathPatch object at 0x000001EBA833C358>, <matplotlib.patches.PathPatch object at 0x000001EBA834C3C8>, <matplotlib.patches.PathPatch object at 0x000001EBA835E400>, <matplotlib.patches.PathPatch object at 0x000001EBA8370438>], 'medians': [<matplotlib.lines.Line2D object at 0x000001EBA83323C8>, <matplotlib.lines.Line2D object at 0x000001EBA8343400>, <matplotlib.lines.Line2D object at 0x000001EBA8356438>, <matplotlib.lines.Line2D object at 0x000001EBA8367470>, <matplotlib.lines.Line2D object at 0x000001EBA83794A8>], 'fliers': [<matplotlib.lines.Line2D object at 0x000001EBA8332BE0>, <matplotlib.lines.Line2D object at 0x000001EBA8343C18>, <matplotlib.lines.Line2D object at 0x000001EBA8356C50>, <matplotlib.lines.Line2D object at 0x000001EBA8367C88>, <matplotlib.lines.Line2D object at 0x000001EBA8379CC0>], 'means': [<matplotlib.lines.Line2D object at 0x000001EBA83327F0>, <matplotlib.lines.Line2D object at 0x000001EBA8343828>, <matplotlib.lines.Line2D object at 0x000001EBA8356860>, <matplotlib.lines.Line2D object at 0x000001EBA8367898>, <matplotlib.lines.Line2D object at 0x000001EBA83798D0>]}
 
In [7]:
# plt.boxplot()繪製
# 分組彙總

df = pd.DataFrame(np.random.rand(10,2), columns=['Col1', 'Col2'] )
df['X'] = pd.Series(['A','A','A','A','A','B','B','B','B','B'])
df['Y'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])
print(df.head())
df.boxplot(by = 'X')
df.boxplot(column=['Col1','Col2'], by=['X','Y'])
# columns:按照數據的列分子圖
# by:按照列分組作箱型圖
 
       Col1      Col2  X  Y
0  0.275776  0.381310  A  A
1  0.446302  0.232518  A  B
2  0.723103  0.587340  A  A
3  0.397370  0.775876  A  B
4  0.382352  0.618421  A  A
Out[7]:
array([<matplotlib.axes._subplots.AxesSubplot object at 0x000001EBA873A198>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x000001EBA8761550>],
      dtype=object)
 
 
In [ ]:
 
In [ ]:
 
In [ ]:
相關文章
相關標籤/搜索