5 小提琴圖Violinplot(代碼下載)
小提琴圖允許可視化一個或多個組的數字變量的分佈。它與箱形圖非常接近,但可以更深入地瞭解密度。小提琴圖特別適用於數據量巨大且無法顯示個別觀察結果的情況。在seaborn中使用violinplot函數繪製小提琴圖,該章節主要內容有:
- 基礎小提琴圖繪製 Basic violinplot
- 小提琴圖樣式自定義 Custom seaborn violinplot
- 小提琴圖顏色自定義 Control color of seaborn violinplot
- 分組小提琴圖 Grouped violinplot
- 小提琴圖組的順序設置 Control order of groups in violinplot
- 顯示小提琴圖上的觀察次數 Show number of observation on violinplot
#調用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 violinplot
- 單個變量 One numerical variable only
- 包含多個分組的單個變量 One variable and several groups
- 多個變量 Several variables
- 水平小提琴圖 Horizontal violinplot
# 單個變量 One numerical variable only
# 如果只有一個數值變量,則最好製作直方圖或密度圖,但是仍然可以用小提琴圖來表示
# Make boxplot for one group only
sns.violinplot( y=df["sepal_length"] );
# 包含多個分組的單個變量 One variable and several groups
# x爲種類名,y爲花萼長度
sns.violinplot( x=df["species"], y=df["sepal_length"] );
# 多個變量 Several variables
# 單獨拿出sepal_length和sepal_width繪製
sns.violinplot(data=df.iloc[:,0:2]);
# 水平小提琴圖 Horizontal violinplot
# 可以通過orient設定方向,但是交換x,y畫水平小提琴圖更好
# Just switch x and y
sns.violinplot( y=df["species"], x=df["sepal_length"] );
2. 小提琴圖樣式自定義 Custom seaborn violinplot
- 線寬自定義 Change line width
- 圖像一般寬度自定義 Change width
# 線寬自定義 Change line width
sns.violinplot( x=df["species"], y=df["sepal_length"], linewidth=5);
# 圖像一般寬度自定義 Change width
sns.violinplot( x=df["species"], y=df["sepal_length"], width=0.3);
3. 小提琴圖顏色自定義 Control color of seaborn violinplot
- 使用調色板 Use a color palette
- 單種顏色 Uniform color
- 指定每個組的顏色 Specify color of each group
- 突出顯示一個組 Highlight a group
# 使用調色板 Use a color palette
sns.violinplot( x=df["species"], y=df["sepal_length"], palette="Blues");
# 單種顏色 Uniform color
sns.violinplot( x=df["species"], y=df["sepal_length"], color="skyblue");
# 指定每個組的顏色 Specify color of each group
# Make a dictionary with one specific color per group:
my_pal = {"versicolor": "g", "setosa": "b", "virginica":"m"}
#plot it
sns.violinplot( x=df["species"], y=df["sepal_length"], palette=my_pal);
# 突出顯示一個組 Highlight a group
# make a vector of color: red for the interesting group, blue for others:
my_pal = {species: "r" if species == "versicolor" else "b" for species in df.species.unique()}
# make the plot
sns.violinplot( x=df["species"], y=df["sepal_length"], palette=my_pal);
4. 分組小提琴圖 Grouped violinplot
# 如果您有一個變量,變量有幾個組和子組,您可能需要製作一個分組的小提琴圖。
df_test = sns.load_dataset('tips')
# Grouped violinplot 分組
sns.violinplot(x="day", y="total_bill", hue="smoker", data=df_test, palette="Pastel1");
5. 小提琴圖組的順序設置 Control order of groups in violinplot
# plot order設置順序就行
sns.violinplot(x='species', y='sepal_length', data=df, order=[ "versicolor", "virginica", "setosa"]);
# Find the order 或者通過設置一定的規則排序
my_order = df.groupby(by=["species"])["sepal_length"].median().iloc[::-1].index
# Give it to the violinplot
sns.violinplot(x='species', y='sepal_length', data=df, order=my_order);
6. 顯示小提琴圖上的觀察次數 Show number of observation on violinplot
# Basic violinplot 基礎小提琴圖像繪製
ax = sns.violinplot(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');