箱形圖(Box-plot)
又稱為盒須圖嗤堰、盒式圖或箱線圖
是一種用作顯示一組數(shù)據(jù)分散情況資料的統(tǒng)計(jì)圖,因形狀如箱子而得名踢匣。它能顯示出一組數(shù)據(jù)的最大值、最小值离唬、中位數(shù)、及上下四分位數(shù)戚哎。
箱形圖繪制須使用常用的統(tǒng)計(jì)量,能提供有關(guān)數(shù)據(jù)位置和分散情況的關(guān)鍵信息型凳,尤其在比較不同的母體數(shù)據(jù)時(shí)更可表現(xiàn)其差異嘱函。
箱形圖的繪制主要包含六個(gè)數(shù)據(jù)節(jié)點(diǎn),需要先將數(shù)據(jù)從大到小進(jìn)行排列往弓,然后分別計(jì)算出它的上邊緣,上四分位數(shù)函似,中位數(shù),下四分位數(shù)缴淋,下邊緣泄朴,還有一個(gè)異常值露氮。
計(jì)算過程:
計(jì)算上四分位數(shù)(Q3)钟沛,中位數(shù),下四分位數(shù)(Q1)
計(jì)算上四分位數(shù)和下四分位數(shù)之間的差值恨统,即四分位數(shù)差(IQR, interquartile range)Q3-Q1
繪制箱線圖的上下范圍,上限為上四分位數(shù)莫绣,下限為下四分位數(shù)。在箱子內(nèi)部中位數(shù)的位置繪制橫線对室。
大于上四分位數(shù)1.5倍四分位數(shù)差的值咖祭,或者小于下四分位數(shù)1.5倍四分位數(shù)差的值,劃為異常值(outliers)么翰。
異常值之外,最靠近上邊緣和下邊緣的兩個(gè)值處浩嫌,畫橫線,作為箱線圖的觸須码耐。
極端異常值,即超出四分位數(shù)差3倍距離的異常值怔匣,用實(shí)心點(diǎn)表示桦沉;較為溫和的異常值每瞒,即處于1.5倍-3倍四分位數(shù)差之間的異常值纯露,用空心點(diǎn)表示。
為箱線圖添加名稱浓利,數(shù)軸等.
最簡(jiǎn)盒型圖
import matplotlib.pyplot as plt
import numpy as np
all_data = [np.random.normal(0, std, 100) for std in range(1, 4)]
fig = plt.figure(figsize=(8, 6))
plt.boxplot(all_data,
notch=False, # box instead of notch shape
sym='rs', # red squares for outliers
vert=True) # vertical box aligmnent
plt.xticks([y + 1 for y in range(len(all_data))], ['x1', 'x2', 'x3'])
plt.xlabel('measurement x')
t = plt.title('Box plot')
plt.show()
自定義顏色填充盒形圖
import matplotlib.pyplot as plt
import numpy as np
all_data = [np.random.normal(0, std, 100) for std in range(1, 4)]
fig = plt.figure(figsize=(8, 6))
bplot = plt.boxplot(all_data,
notch=False, # notch shape
vert=True, # vertical box aligmnent
patch_artist=True) # fill with color
colors = ['pink', 'lightblue', 'lightgreen']
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
plt.xticks([y + 1 for y in range(len(all_data))], ['x1', 'x2', 'x3'])
plt.xlabel('measurement x')
t = plt.title('Box plot')
plt.show()
小提琴圖
小提琴圖 (Violin Plot)是用來展示多組數(shù)據(jù)的分布狀態(tài)以及概率密度。這種圖表結(jié)合了箱形圖和密度圖的特征贷掖,主要用來顯示數(shù)據(jù)的分布形狀。跟箱形圖類似昆咽,但是在密度層面展示更好牙甫。在數(shù)據(jù)量非常大不方便一個(gè)一個(gè)展示的時(shí)候小提琴圖特別適用掷酗。
小提琴圖概念圖
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(figsize=(12, 5))
all_data = [np.random.normal(0, std, 100) for std in range(6, 10)]
axes.violinplot(all_data,
showmeans=False,
showmedians=True
)
axes.set_title('violin plot')
# adding horizontal grid lines
axes.yaxis.grid(True)
axes.set_xticks([y + 1 for y in range(len(all_data))], )
axes.set_xlabel('xlabel')
axes.set_ylabel('ylabel')
plt.setp(axes, xticks=[y + 1 for y in range(len(all_data))],
xticklabels=['x1', 'x2', 'x3', 'x4'],
)
plt.show()