seaborn是專門用于統(tǒng)計數(shù)據(jù)可視化的包,可媲美R語言中的ggplot2包。本文介紹用seaborn繪制盒形圖。
環(huán)境
- python3.9
- win10 64bit
- seaborn==0.11.1
- matplotlib==3.3.4
- pandas==1.2.1
數(shù)據(jù)
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
# 設(shè)置
pd.options.display.notebook_repr_html=False # 表格顯示
plt.rcParams['figure.dpi'] = 75 # 圖形分辨率
sns.set_theme(style='darkgrid') # 圖形主題
# 加載數(shù)據(jù)
tips=pd.read_csv(r'https://gitee.com/nicedouble/seaborn-data/raw/master/tips.csv')
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
繪制
在seaborn中,繪制盒形圖的函數(shù)有boxplot
和catplot
。
seaborn
繪制盒形圖最簡單的方式是使用boxplot
方法,指定data
參數(shù)和x
或y
參數(shù)。
# 盒形圖,繪制在x軸上
sns.boxplot(data=tips,x='total_bill')
plt.show()
box_6_0.png
設(shè)置y
參數(shù)時,盒形圖會繪制在y軸上。
# 盒形圖,繪制在y軸上
sns.boxplot(data=tips,y='total_bill')
plt.show()
box_8_0.png
如果只設(shè)置data
參數(shù),seaborn
會把數(shù)據(jù)當成寬型數(shù)據(jù),自動繪制所有的數(shù)值型變量的盒形圖。
# 自動繪制所有數(shù)值型變量的盒形圖
sns.boxplot(data=tips)
plt.show()
box_10_0.png
同時設(shè)置x
和y
參數(shù),繪制多個盒形圖。x
和y
參數(shù)需要一個為類別型變量,一個為數(shù)值型變量。
# 多個盒形圖
sns.boxplot(data=tips,x="day", y="total_bill")
plt.show()
box_12_0.png
調(diào)整
設(shè)置linewidth
參數(shù),可以調(diào)整盒形圖線寬。
# 粗線盒形圖
sns.boxplot(data=tips,x="total_bill",linewidth=5)
plt.show()
box_14_0.png
設(shè)置參數(shù)orient='h'
,可以使盒形圖水平放置。
# 水平放置盒形圖
sns.boxplot(data=tips,orient='h')
plt.show()
box_16_0.png
分組盒形圖
設(shè)置hue
參數(shù),可以繪制分組盒形圖。
# 分組盒形圖
sns.boxplot(data=tips,x="day", y="total_bill", hue="smoker")
plt.show()
box_18_0.png
分面盒形圖
使用catplot
繪制分面盒形圖,設(shè)置參數(shù)kind='box'
,設(shè)置col
或row
控制分面行為。
# 分面盒形圖
sns.catplot(data=tips,x='day',y='total_bill',hue='smoker',col='sex',kind='box')
plt.show()
box_20_0.png
更多參考seaborn盒形圖