天天看點

python資料分析與可視化——利用Seaborn進行繪圖

利用Seaborn進行繪圖

下面例子中所用資料下載下傳位址——>iris.csv

Matplotlib繪圖基本模仿MATLAB繪圖庫,其繪圖風格和MATLAB類似。由于MATLAB繪圖風格偏古典,是以,Python開源社群開發了Seaborn繪圖子產品,對Matplotlib進行封裝,繪圖效果更符合現代人的審美。

Seaborn屬于Matplotlib的一個進階接口,使得作圖更加容易。在多數情況下使用Seaborn能做出很具吸引力的圖,而使用Matplotlib可以制作具有更多特色的圖。應該把Seaborn視為iris.csvMatplotlib的補充,而不是替代物。

使用Seaborn時,使用的導入慣例為:

import seaborn as sns

風格設定用以設定繪圖的背景色、風格、字型、字型等。

Seaborn通過set函數實作風格設定。

seaborn.set(context=‘notebook’, style=‘darkgrid’, palette=‘deep’, font=‘sans-serif’, font_scale=1, color_codes=True, rc=None)

利用seaborn.set進行風格設定

import seaborn as sns
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def sinplot(flip=2):
    x = np.linspace(0,20, 50)
    for i in range(1,5):
        plt.plot(x, np.cos(x + i * 0.8) * (9 - 2*i) * flip)
sinplot()

           
python資料分析與可視化——利用Seaborn進行繪圖
sns.set(style='darkgrid',font_scale=1.5)
sinplot()
           
python資料分析與可視化——利用Seaborn進行繪圖

如果需要轉換為seaborn預設的繪圖設定,隻需調用sns.set( )方法即可。

sns.set()
sinplot()
           

設定主題

利用set_style( )是用來設定主題的。

Seaborn有五個預設好的主題: darkgrid, whitegrid,dark,white,和 ticks,預設為darkgrid。

sns.set_style("whitegrid")  
sinplot()
           
python資料分析與可視化——利用Seaborn進行繪圖

Seaborn将matplotlib的參數劃分為兩個獨立的組合。第一組是設定繪圖的外觀風格的,第二組主要将繪圖的各種元素按比例縮放的,以至可以嵌入到不同的背景環境中。控制這些參數的接口主要有兩對方法:

控制風格:axes_style(), set_style()

縮放繪圖:plotting_context(), set_context()

每對方法中的第一個方法(axes_style(), plotting_context())會傳回一組字典參數,而第二個方法(set_style(), set_context())會設定matplotlib的預設參數。

利用set_style( )是用來設定主題的。Seaborn有五個預設的主題: darkgrid, whitegrid,dark,white,和 ticks,預設為darkgrid。

sns.set_style("whitegrid")  
sinplot()
           
python資料分析與可視化——利用Seaborn進行繪圖

在seaborn中,可以利用despine()方法移除繪圖中頂部和右側的軸線。

sinplot()
sns.despine()
           
python資料分析與可視化——利用Seaborn進行繪圖

despine()方法中可以利用offset參數講軸線進行偏置,另外,當刻度沒有完全覆寫整個坐标軸的的範圍時,利用trim參數限制已有坐标軸的範圍。

sinplot()
sns.despine(offset=20, trim=True)
           
python資料分析與可視化——利用Seaborn進行繪圖

也可以通過despine()控制哪個脊柱将被移除。

sinplot()
sns.despine(left=True)
           
python資料分析與可視化——利用Seaborn進行繪圖

也可以通過despine()控制哪個脊柱将被移除。

sinplot()
sns.set(style='whitegrid',palette='muted',color_codes=True)
sns.despine(left=True,bottom=True)
           
python資料分析與可視化——利用Seaborn進行繪圖

除了選用預設的風格外,可以利用with 語句使用axes_style()方法設定臨時繪圖參數。

with sns.axes_style("darkgrid"):
    plt.subplot(2,1,1)
    sinplot( )
plt.subplot(2,1, 2)
sinplot(-1)
           
python資料分析與可視化——利用Seaborn進行繪圖

seaborn中通過set_context()設定縮放參數,預設的參數有paper, notebook, talk, poster。預設為notebook。

sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()
           
python資料分析與可視化——利用Seaborn進行繪圖
sns.set_context("paper")
sinplot()
           
python資料分析與可視化——利用Seaborn進行繪圖
sns.set_context("notebook", font_scale=1.8, rc={"lines.linewidth": 1.5})
sinplot()
           
python資料分析與可視化——利用Seaborn進行繪圖

常用的繪圖

直方圖和密度曲線圖

Seaborn中利用distplot( )和 kdeplot( )繪制直方圖和密度曲線圖,distplot( )為hist加強版,預設情況下繪制一個直方圖,并嵌套一個對應的密度圖。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set(palette="muted",color_codes=True)
rs=np.random.RandomState(10)
d=rs.normal(size=100)
f,axes=plt.subplots(2, 2, figsize=(7, 7), sharex=True)
sns.distplot(d, kde=False, color="b", ax=axes[0,0])
sns.distplot(d, hist=False, rug=True, color="r", ax=axes[0,1])
sns.distplot(d, hist=False,color="g", kde_kws={"shade":True}, ax=axes[1,0])
sns.distplot(d, color="m", ax=axes[1,1])
plt.show()

           
python資料分析與可視化——利用Seaborn進行繪圖

散點圖

在Seaborn中,利用stripplot繪制各變量在每個類别的值。

例:在iris資料集中,顯示Petal.Width在Species上值的分布

sns.set(style='white',color_codes=True) #設定樣式 
sns.stripplot(x=df_iris['Species'],y= df_iris['Petal.Width'],data=df_iris)
sns.despine()   #去坐标軸
           
python資料分析與可視化——利用Seaborn進行繪圖

如果需要看清每個資料點,可以使用swarmplot函數

sns.swarmplot(x=df_iris['Species'],y= df_iris['Petal.Width'],data=df_iris)
sns.despine()   #去坐标軸
           
python資料分析與可視化——利用Seaborn進行繪圖

箱型圖

有時候,散點圖表達的值的分布資訊有限,是以需要一些其它的繪圖。箱線圖可以觀察四分位數、中位數和極值。Seaborn中利用boxplot( )繪制箱線圖。

df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.boxplot(x=df_iris['Species'],y = df_iris['Petal.Width'])  
plt.show()
           
python資料分析與可視化——利用Seaborn進行繪圖
df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.set(style="ticks")  
sns.boxplot(x=df_iris['Species'],y = df_iris['Petal.Width'])  
plt.show()
           
python資料分析與可視化——利用Seaborn進行繪圖

pairplot

在seaborn中利用 pairplot()實作資料特征的兩兩對比。預設是所有特征,可以通過vars參數指定部分特征。

pairplot主要展現的是變量兩兩之間的關系(線性或非線性,有無較為明顯的相關關系)

df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.set(style="ticks")  
g = sns.pairplot(df_iris,vars=['Sepal.Length', 'Petal.Length'])
           
python資料分析與可視化——利用Seaborn進行繪圖

小提琴圖

小提琴圖其實是箱線圖與核密度圖的結合,箱線圖展示了分位數的位置,小提琴圖則展示了任意位置的密度,通過小提琴圖可以知道哪些位置的密度較高。在圖中,白點是中位數,黑色盒型的範圍是下四分位點到上四分位點,細黑線表示須。外部形狀即為核密度估計(在機率論中用來估計未知的密度函數,屬于非參數檢驗方法之一)。

sns.set_style("whitegrid")
df_iris=pd.read_csv('D:\dataset\iris.csv')
ax = sns.violinplot(x=df_iris['Petal.Length'])
           
python資料分析與可視化——利用Seaborn進行繪圖

柱狀圖

在Seaborn中使用barplot函數繪制柱狀圖,預設情況下,繪制的y軸是平均值。

df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.barplot(x=df_iris['Species'],y=df_iris['Petal.Length'],data=df_iris)

           
python資料分析與可視化——利用Seaborn進行繪圖

在柱狀圖中,經常會繪制類别的計數柱狀圖,在matplotlib中需要對DataFrame進行計算,而在Seaborn中則使用countplot函數即可。

python資料分析與可視化——利用Seaborn進行繪圖

多變量圖

在matplotlib中,為了繪制兩個變量的分布關系,常使用散點圖的方法。在Seaborn中,使用jointplot函數繪制一個多面闆圖,不僅可以顯示兩個變量的關系,還可以顯示每個單變量的分布情況。

python資料分析與可視化——利用Seaborn進行繪圖

在jointplot函數中,改變kind參數為kde,但變量的分布就用密度圖來代替,而散點圖則會被等高線圖代替。

python資料分析與可視化——利用Seaborn進行繪圖

回歸圖

繪制回歸圖可以揭示兩個變量間的線性關系。Seaborn中,使用regplot函數繪制回歸圖。

python資料分析與可視化——利用Seaborn進行繪圖