1 箱形圖Boxplot(代碼下載)
Boxplot可能是最常見的圖形類型之一。它能夠很好表示數據中的分佈規律。箱型圖方框的末尾顯示了上下四分位數。極線顯示最高和最低值,不包括異常值。seaborn中用boxplot函數製作箱形圖。該章節主要內容有:
- 基礎箱形圖繪製 Basic boxplot and input format
- 自定義外觀 Custom boxplot appearance
- 箱型圖的顏色設置 Control colors of boxplot
- 分組箱圖 Grouped Boxplot
- 箱圖的順序設置 Control order of boxplot
- 添加散點分佈 Add jitter over boxplot
- 顯示各類的樣本數 Show number of observation on boxplot
- 箱形圖隱藏的數據處理 Hidden data under boxplot
#調用seaborn
import seaborn as sns
#調用seaborn自帶數據集
df = sns.load_dataset('iris')
#顯示數據集
df.head()
sepal_length | sepal_width | petal_length | petal_width | species | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
1. 基礎箱形圖繪製 Basic boxplot and input format
- 一個數值變量 One numerical variable only
- 一個數值變量和多個分組 One numerical variable, and several groups
- 多個數值變量 Several numerical variable
- 水平箱型圖 Horizontal boxplot with seaborn
# 一個數值變量 One numerical variable only
# 如果您只有一個數字變量,則可以使用此代碼獲得僅包含一個組的箱線圖。
# Make boxplot for one group only
# 顯示花萼長度sepal_length
sns.boxplot( y=df["sepal_length"] );
# 一個數值變量和多個分組 One numerical variable, and several groups
# 假設我們想要研究數值變量的分佈,但是對於每個組分別進行研究。在這裏,我們研究了3種花的萼片長度。
# x花的品種,y花萼長度
sns.boxplot( x=df["species"], y=df["sepal_length"] );
# 多個數值變量 Several numerical variable
# 可以研究幾個數值變量的分佈,比如說萼片的長度和寬度:
sns.boxplot(data=df.iloc[:,0:2]);
# 水平箱型圖 Horizontal boxplot with seaborn
# 用seaborn將你的箱圖水平轉動是非常簡單的。您可以切換x和y屬性,或使用選項orient ="h"
sns.boxplot( y=df["species"], x=df["sepal_length"] );
2. 自定義外觀 Custom boxplot appearance
- 自定義線寬 Custom line width
- 添加缺口 Add notch
- 控制箱的尺寸 Control box sizes
# 自定義線寬 Custom line width
# Change line width
# 根據linewidth改變線條寬度
sns.boxplot( x=df["species"], y=df["sepal_length"], linewidth=5);
# 添加缺口 Add notch
# notch設置爲true即可
sns.boxplot( x=df["species"], y=df["sepal_length"], notch=True);
# 控制箱的尺寸 Control box sizes
# Change width
sns.boxplot( x=df["species"], y=df["sepal_length"], width=0.3);
3. 箱型圖的顏色設置 Control colors of boxplot
- 調色板的使用 Use a color palette
- 單種顏色的使用 Uniform color
- 每組的特定顏色 Specific color for each group
- 單組高亮 Highlight a group
- 添加透明色 Add transparency to color
# 調色板的使用 Use a color palette
# Python提出了幾種調色板。您可以像Set1,Set2,Set3,Paired,BuPu一樣調用RColorBrewer調色板,還有Blues或BuGn_r等調色板。
# 調色板各種顏色見 http://www.r-graph-gallery.com/38-rcolorbrewers-palettes/
# t通過plaette調用調色板,Use a color palette
sns.boxplot( x=df["species"], y=df["sepal_length"], palette="Blues");
# 單種顏色的使用 Uniform color
# 當然您可以輕鬆地爲每個盒子應用同樣的顏色。最常見的是b: blue
# 顏色列表 https://matplotlib.org/examples/color/named_colors.html
sns.boxplot( x=df["species"], y=df["sepal_length"], color="skyblue");
# 每組的特定顏色 Specific color for each group
# 用不用顏色描繪不同種類的花
my_pal = {"versicolor": "g", "setosa": "b", "virginica":"m"}
sns.boxplot( x=df["species"], y=df["sepal_length"], palette=my_pal);
# 單組高亮 Highlight a group
# 設定某一組爲紅色,其他組爲藍色
my_pal = {species: "r" if species == "versicolor" else "b" for species in df.species.unique()}
sns.boxplot( x=df["species"], y=df["sepal_length"], palette=my_pal);
# 添加透明色 Add transparency to color
# usual boxplot 正常繪圖
ax = sns.boxplot(x='species', y='sepal_length', data=df);
# Add transparency to colors 設置透明色
for patch in ax.artists:
r, g, b, a = patch.get_facecolor()
patch.set_facecolor((r, g, b, .3))
4. 分組箱圖 Grouped Boxplot
# 當您有一個數值變量,幾個組和子組時,將使用分組箱圖。使用seaborn很容易實現。Y是您的數字變量,x是組列,而hue是子組列。
# 調用tips數據集
df_tips = sns.load_dataset('tips')
df_tips.head()
total_bill | tip | sex | smoker | day | time | size | |
---|---|---|---|---|---|---|---|
0 | 16.99 | 1.01 | Female | No | Sun | Dinner | 2 |
1 | 10.34 | 1.66 | Male | No | Sun | Dinner | 3 |
2 | 21.01 | 3.50 | Male | No | Sun | Dinner | 3 |
3 | 23.68 | 3.31 | Male | No | Sun | Dinner | 2 |
4 | 24.59 | 3.61 | Female | No | Sun | Dinner | 4 |
# Grouped boxplot 分組箱圖
# x日期,y餐費,hue自組列,palette調色盤
sns.boxplot(x="day", y="total_bill", hue="smoker", data=df_tips, palette="Set1");
5. 箱圖的順序設置 Control order of boxplot
#如果您按特定順序設定組,則箱圖通常會提供更多信息。這對seaborn來說是可行的。
# specific order 通過order自定義組
p1=sns.boxplot(x='species', y='sepal_length', data=df, order=["virginica", "versicolor", "setosa"]);
# 中位數由大到小排列
# Find the order 設定中位數
my_order = df.groupby(by=["species"])["sepal_length"].median().iloc[::-1].index
# Give it to the boxplot
sns.boxplot(x='species', y='sepal_length', data=df, order=my_order);
6. 添加散點分佈 Add jitter over boxplot
# 可以在箱線圖上添加每種類別的散點分佈情況
# Usual boxplot 正常繪圖
ax = sns.boxplot(x='species', y='sepal_length', data=df)
# Add jitter with the swarmplot function 添加散點分佈
ax = sns.swarmplot(x='species', y='sepal_length', data=df, color="grey")
7. 顯示各類的樣本數 Show number of observation on boxplot
# 顯示每個組的觀察次數可能很有用
# 基礎的箱形圖
ax = sns.boxplot(x="species", y="sepal_length", data=df)
# Calculate number of obs per group & median to position labels
# 計算各個種類的中位數
medians = df.groupby(['species'])['sepal_length'].median().values
# 統計各個種類的樣本數
nobs = df['species'].value_counts().values
nobs = [str(x) for x in nobs.tolist()]
nobs = ["n: " + i for i in nobs]
# Add it to the plot
pos = range(len(nobs))
for tick,label in zip(pos,ax.get_xticklabels()):
ax.text(pos[tick], medians[tick] + 0.03, nobs[tick], horizontalalignment='center', size='x-small', color='w', weight='semibold')
8. 箱形圖隱藏的數據處理 Hidden data under boxplot
- 添加分佈散點圖 boxplot with jitter
- 使用小提琴圖 use violinplot
箱形圖總結了幾個組的數值變量的分佈。但是箱形圖的問題不僅是丟失信息,這可能會結果有偏差。如果我們考慮下面的箱形圖,很容易得出結論,'C’組的價值高於其他組。但是,我們無法看到每個組中點的基本分佈是什麼,也沒有觀察每個組的觀察次數。所以我們需要對隱藏的數據進行處理
# libraries and data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Dataset:
a = pd.DataFrame({ 'group' : np.repeat('A',500), 'value': np.random.normal(10, 5, 500) })
b = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(13, 1.2, 500) })
c = pd.DataFrame({ 'group' : np.repeat('B',500), 'value': np.random.normal(18, 1.2, 500) })
d = pd.DataFrame({ 'group' : np.repeat('C',20), 'value': np.random.normal(25, 4, 20) })
e = pd.DataFrame({ 'group' : np.repeat('D',100), 'value': np.random.uniform(12, size=100) })
df=a.append(b).append(c).append(d).append(e)
# Usual boxplot
sns.boxplot(x='group', y='value', data=df);
# 添加分佈散點圖 boxplot with jitter
ax = sns.boxplot(x='group', y='value', data=df)
# 通過stripplot添加分佈散點圖,jitter設置數據間距
ax = sns.stripplot(x='group', y='value', data=df, color="orange", jitter=0.2, size=2.5)
plt.title("Boxplot with jitter", loc="left")
Text(0.0, 1.0, 'Boxplot with jitter')
# 使用小提琴圖 use violinplot
sns.violinplot( x='group', y='value', data=df)
plt.title("Violin plot", loc="left")
Text(0.0, 1.0, 'Violin plot')