??照例引用官方介紹“Seaborn是一個帶著定制主題和高級界面控制的Matplotlib擴展包,能讓繪圖變得更輕松”,這里我們只需要知道Seaborn是一個用于數據可視化的包就行了,可以讓我們用最少的代碼去繪制一些描述性統計的圖,便于找尋各維度變量之間的特征和關系,需要快速了解Seaborn的,可以查看Seaborn官方教程。接下來我們將通過一個經典數據集——鳶尾花來初步認識Seaborn。
0.開始前的準備
??Iris鳶尾花數據集是一個經典數據集,在統計學習和機器學習領域都經常被用作示例。數據集內包含3類共150條記錄,每類各50個數據,每個數據都有4個屬性:花萼長度、花萼寬度、花瓣長度、花瓣寬度,可以通過這4個屬性預測鳶尾花卉屬于(iris-setosa,iris-versicolour,iris-virginica)中的哪一類,但據說現實中,這三種花的基本判別依據其實是種子(因為花瓣非常容易枯萎)。
??在分析這個數據集之前,讓我們先做好相關準備,包括導入相關包、導入數據集等。
# 導入相關包
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 導入數據集,也可以通過iris = sns.load_dataset("iris") 導入
iris = pd.read_csv('data/iris.csv', header=None)
#設置列名
iris.columns = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'species']
#查看數據集信息
iris.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
sepal-length 150 non-null float64
sepal-width 150 non-null float64
petal-length 150 non-null float64
petal-width 150 non-null float64
species 150 non-null object
dtypes: float64(4), object(1)
memory usage: 5.9+ KB
# 查看數據集頭5條記錄
iris.head()
# 查看鳶尾花的所有種類
iris['species'].unique()
array(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'], dtype=object)
??完成這些準備工作后,我們可以通過seaborn對該數據集進行可視化分析。
1.Stripplot & Swarmplot
# 設置seaborn樣式
sns.set_style("whitegrid")
seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=False, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
??Stripplot主要用于繪制散點圖,下面將鳶尾花數據集中的花萼長度屬性按品種分類繪制成散點圖分析:
ax = sns.stripplot(x="species", y="sepal-length", data=iris)
??通過jitter
屬性為散點圖設置抖動,以便更好地觀察數據。
ax = sns.stripplot(x="species", y="sepal-length", data=iris, jitter=True)
ax = sns.stripplot(x="species", y="sepal-length", data=iris, jitter=0.05)
??改變軸向觀察數據。
ax = sns.stripplot(x="sepal-length", y="species", data=iris, jitter=0.05)
??通過改變顏色、樣式、大小等更好地觀察數據。
antV = ['#1890FF', '#2FC25B', '#FACC14', '#223273', '#8543E0', '#13C2C2', '#3436c7', '#F04864']
ax = sns.stripplot(x="sepal-length", y="species", data=iris, jitter=0.05, palette=antV)
ax = sns.stripplot("species", "sepal-length", data=iris, palette="Set2", size=12, marker="D",
jitter=0.05, edgecolor="gray", alpha=.25)
seaborn.swarmplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
??Swarmplot也是繪制散點圖,但它會通過算法,在類別坐標軸的方向上延展那些原本重合的點,與通過jitter
屬性增加抖動有異曲同工之妙。
ax = sns.swarmplot(x="species", y="sepal-length", data=iris)
??現在我們通過Swarmplot觀察花萼長度、花萼寬度、花瓣長度、花瓣寬度與類別之間的關系。
f, axes = plt.subplots(2, 2, figsize=(12, 12), sharex=True)
sns.despine(left=True)
sns.swarmplot(x="species", y="sepal-length", data=iris, palette=antV, ax=axes[0, 0])
sns.swarmplot(x="species", y="sepal-width", data=iris, palette=antV, ax=axes[0, 1])
sns.swarmplot(x="species", y="petal-length", data=iris, palette=antV, ax=axes[1, 0])
sns.swarmplot(x="species", y="petal-width", data=iris, palette=antV, ax=axes[1, 1])
plt.setp(axes, yticks=[])
plt.tight_layout()
2.Boxplot & Violinplot
seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None,
saturation=0.75, width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, notch=False, ax=None, **kwargs)
??通過Boxplot可以看到數據的最大值、上四分位數Q3、中位數、下四分位數Q1、最小值和異常值的分布。
f, axes = plt.subplots(2, 2, figsize=(12, 12), sharex=True)
sns.despine(left=True)
sns.boxplot(x="species", y="sepal-length", data=iris, palette='Set2', ax=axes[0, 0])
sns.boxplot(x="species", y="sepal-width", data=iris, palette='Set2', ax=axes[0, 1])
sns.boxplot(x="species", y="petal-length", data=iris, palette='Set2', ax=axes[1, 0])
sns.boxplot(x="species", y="petal-width", data=iris, palette='Set2', ax=axes[1, 1])
plt.setp(axes, yticks=[])
plt.tight_layout()
seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, bw='scott', cut=2, scale='area', scale_hue=True, gridsize=100, width=0.8, inner='box', split=False, dodge=True, orient=None, linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)
??Violinplot與Boxplot相似,但其圖形如同小提琴般,可以更好地展現出數據的量化形態。
# Set up the matplotlib figure
f, axes = plt.subplots(2, 2, figsize=(12, 12), sharex=True)
sns.despine(left=True)
sns.violinplot(x="species", y="sepal-length", data=iris, palette='Set2', ax=axes[0, 0])
sns.violinplot(x="species", y="sepal-width", data=iris, palette='Set2', ax=axes[0, 1])
sns.violinplot(x="species", y="petal-length", data=iris, palette='Set2', ax=axes[1, 0])
sns.violinplot(x="species", y="petal-width", data=iris, palette='Set2', ax=axes[1, 1])
plt.setp(axes, yticks=[])
plt.tight_layout()
??可以Stripplot & Swarmplot與Boxplot & Violinplot將相組合,以更好地查看數據分布情況。
ax = sns.violinplot(x="species", y="sepal-length", data=iris, palette='Set2')
ax = sns.swarmplot(x="species", y="sepal-length", data=iris, color="white", edgecolor="gray")
3.Barplot
seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean>, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, saturation=0.75, errcolor='.26', errwidth=None, capsize=None, dodge=True, ax=None, **kwargs)
??Barplot主要是繪制條形圖,利用條形的高度反映數值變量的集中趨勢,在條形頂部還有誤差棒。
f, axes = plt.subplots(2, 2, figsize=(10, 10), sharex=True)
sns.despine(left=True)
sns.barplot(x="species", y="sepal-length", data=iris, palette='Set2', ax=axes[0, 0])
sns.barplot(x="species", y="sepal-width", data=iris, palette='Set2', ax=axes[0, 1])
sns.barplot(x="species", y="petal-length", data=iris, palette='Set2', ax=axes[1, 0])
sns.barplot(x="species", y="petal-width", data=iris, palette='Set2', ax=axes[1, 1])
plt.setp(axes, yticks=[])
plt.tight_layout()
4.Countplot
seaborn.countplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True, ax=None, **kwargs)
??Countplot可以直觀地查看每個類別下有多少個觀察值。
ax = sns.countplot(y="species", data=iris, palette="Set3")
5.Pointplot
seaborn.pointplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean>, ci=95, n_boot=1000, units=None, markers='o', linestyles='-', dodge=False, join=True, scale=1, orient=None, color=None, palette=None, errwidth=None, capsize=None, ax=None, **kwargs)
??Pointplot可以通過斜率很容易地看出各類別間的主要關系。
f, axes = plt.subplots(2, 2, figsize=(10, 10), sharex=True)
sns.despine(left=True)
sns.pointplot(x="species", y="sepal-length", data=iris, ax=axes[0, 0])
sns.pointplot(x="species", y="sepal-width", data=iris, ax=axes[0, 1])
sns.pointplot(x="species", y="petal-length", data=iris, ax=axes[1, 0])
sns.pointplot(x="species", y="petal-width", data=iris, ax=axes[1, 1])
plt.setp(axes, yticks=[])
plt.tight_layout()
6. Factorplot
seaborn.factorplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=<function mean>, ci=95, n_boot=1000, units=None, order=None, hue_order=None, row_order=None, col_order=None, kind='point', size=4, aspect=1, orient=None, color=None, palette=None, legend=True, legend_out=True, sharex=True, sharey=True, margin_titles=False, facet_kws=None, **kwargs)
??Factorplot將上述的函數與FacetGrid
結合起來,通過設置kind
屬性,可以變化成不同的圖形。
sns.factorplot(x="species", y="sepal-length", data=iris, kind="violin")
sns.factorplot(x="species", y="sepal-width", data=iris, kind="box");
7. PairGrid
class seaborn.PairGrid(data, hue=None, hue_order=None, palette=None, hue_kws=None, vars=None, x_vars=None, y_vars=None, diag_sharey=True, size=2.5, aspect=1, despine=True, dropna=True)
??PairGrid可以用于繪制展現數據集內多個變量之間關系的矩陣圖。
g = sns.PairGrid(data=iris, palette=antV, hue="species")
g = g.map(plt.scatter)
g = sns.PairGrid(data=iris, palette=antV, hue="species")
g = g.map_diag(plt.hist)
g = g.map_offdiag(plt.scatter)
g = g.add_legend()