seaborn模塊的基本使用


Seaborn是基於matplotlib的Python可視化庫。 它提供了一個高級界面來繪制有吸引力的統計圖形。Seaborn其實是在matplotlib的基礎上進行了更高級的API封裝,從而使得作圖更加容易,不需要經過大量的調整就能使你的圖變得精致。但應強調的是,應該把Seaborn視為matplotlib的補充,而不是替代物。

 

一、整體布局風格設置

import seaborn as sns import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline #這句話的意思就是可以直接顯示圖

def sinplot(flip = 1): x = np.linspace(0, 14, 100) for i in range(1, 7): plt.plot(x, np.sin(x + i*0.5) * (7 - i) * flip) sinplot()#采用的是matplot默認的一些參數畫圖

 

 

#接下來采用的是seaborn的畫圖的風格,首先看看默認的變化
sns.set() sinplot()

 

 

#seaborn主要分為五種主題風格:darkgrid whitegrid dark white ticks
sns.set_style("whitegrid") data = np.random.normal(size=(20, 6)) + np.arange(6) / 2 sns.boxplot(data=data)

高斯分布的概率密度函數

              

numpy中

numpy.random.normal(loc=0.0, scale=1.0, size=None)  

參數的意義為:

  loc:float

  概率分布的均值,對應着整個分布的中心center

  scale:float

  概率分布的標准差,對應於分布的寬度,scale越大越矮胖,scale越小,越瘦高

  size:int or tuple of ints

  輸出的shape,默認為None,只輸出一個值

  我們更經常會用到np.random.randn(size)所謂標准正太分布(μ=0, σ=1),對應於np.random.normal(loc=0, scale=1, size)

所以上面從正態分布隨機產生20*6的二維數組,加上后面的6*1的一維數組。

 

boxplot 箱線圖

"盒式圖" 或叫 "盒須圖" "箱形圖",,其繪制須使用常用的統計量,能提供有關數據位置和分散情況的關鍵信息,尤其在比較不同的母體數據時更可表現其差異。

如上圖所示,標示了圖中每條線表示的含義,其中應用到了分位值(數)的概念。

主要包含五個數據節點,將一組數據從大到小排列,分別計算出他的上邊緣,上四分位數,中位數,下四分位數,下邊緣。

具體用法如下: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, fliersize=5, linewidth=None, whis=1.5, notch=False, ax=None, **kwargs)

Parameters:

x, y, hue: names of variables in data or vector data, optional #設置 x,y 以及顏色控制的變量

Inputs for plotting long-form data. See examples for interpretation.

data : DataFrame, array, or list of arrays, optional #設置輸入的數據集

Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.

order, hue_order : lists of strings, optional #控制變量繪圖的順序

Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.

 

sns.set_style("dark") sinplot()

 

 

sns.set_style("white") sinplot()

 

 

sns.set_style("ticks") sinplot()

 

 

sinplot() sns.despine() #在ticks基礎上去掉上面的和右邊的端線

 

 

二、風格細節的設置

import seaborn as sns import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline #這句話的意思就是可以直接顯示圖
sns.violinplot(data) sns.despine(offset=30) #顯示的是圖形的最低點距橫軸的距離

 

 

sns.set_style("whitegrid") sns.boxplot(data=data, palette="deep") sns.despine(left = True) #把左邊的軸去掉了。

 

 

with sns.axes_style("darkgrid"): #通過with可以顯示一種一個子圖的風格。
    plt.subplot(211) sinplot() plt.subplot(212) sinplot(-1)

 

 

#另一種調節圖中線的粗細程度的風格:paper talk poster notebook,前三種風格的線越來越粗,最后一個notebook是可以通過參數的修改的
sns.set() sns.set_context("paper") plt.figure(figsize=(8, 6)) sinplot()

 

 

sns.set_context("talk") plt.figure(figsize=(8, 6)) sinplot()

 

 

sns.set_context("poster") plt.figure(figsize=(8, 6)) sinplot()

 

 

 

sns.set_context("notebook", font_scale = 2, rc={"lines.linewidth" : 4.5}) #這個是可以的設置的參數的,font_scale是改變坐標軸上的大小,rc中的line.linewidth是改變線的粗細
 plt.figure(figsize=(8, 6)) sinplot()

 

 

三、調色板

color_palette()能傳入任何Matplotlib所支持的顏色

set_palette()設置所有圖的顏色

#顯示默認的顏色 deep, muted, pastel, bright, dark, colorblind......
current_palette = sns.color_palette() 

sns.palplot(current_palette)

 

 圓形畫板

當需要更多分類要區分時,最簡單的方法就是在一個圓形的顏色空間中畫出均勻間隔的顏色(這樣的色調會保持亮度和飽和度不變)。這是大多數的需要使用的比默認顏色循環中的設置的顏色更多的默認方案。

最常用的方法是使用hls的顏色空間,這是RGB值的一個簡單轉換。

#比如我想畫個12個不同的顏色
sns.palplot(sns.color_palette("hls", 12))

 

 

data = np.random.normal(size = (20, 8)) + np.arange(8) / 2

sns.boxplot(data = data, palette = sns.color_palette("hls", 8))

 

 

hls_palette()函數來控制顏色的亮度和飽和度

l------亮度 lightness

s------飽和 saturation

sns.palplot(sns.hls_palette(8, l = 0.3, s = 0.8))

 

 

sns.palplot(sns.color_palette("Paired", 8)) #Paired意思是比如8就是4對顏色,每一對顏色都是一淺一深。

 

 

使用xkcd顏色來命名顏色

xkcd包含了一套眾包努力的針對隨機RGB色的命名。產生了954個可以隨機通過xkcd_rgb字典中調用的命名顏色。

plt.plot([0, 1], [0, 1], sns.xkcd_rgb["pale red"], lw=3)
    
plt.plot([0, 1], [0, 2], sns.xkcd_rgb["medium green"], lw=3)

plt.plot([0, 1], [0, 3], sns.xkcd_rgb["denim blue"], lw=3)

 

 

#其他xkcd的一些顏色
colors = ["windows blue", "amber", "greyish", "faded green", "dusty purple"]

sns.palplot(sns.xkcd_palette(colors))

 

 

連續色板

色彩隨數據變換,比如數據越來越重要則顏色越來越深

sns.palplot(sns.color_palette("Blues"))

 

 

如果想要翻轉漸變,可以在面板名稱中添加一個_r后綴

sns.palplot(sns.color_palette("BuGn_r"))

 

 

cubehelix_palette()調色板

色調線性變換

sns.palplot(sns.color_palette("cubehelix", 8))

 

 

sns.palplot(sns.cubehelix_palette(8, start = 0.5, rot = -0.75))

 

 

sns.palplot(sns.cubehelix_palette(8, start = 0.75, rot = -0.150))

 

 

light_palette()和dark_palette()調用定制連續調色板

sns.palplot(sns.light_palette("green"))

 

 

sns.palplot(sns.dark_palette("purple"))

 

 

sns.palplot(sns.light_palette("navy", reverse=True))

 

 

四、單變量分析繪圖

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy import stats, integrate
%matplotlib inline 

x = np.random.normal(size = 100) #正態分布

sns.distplot(x, kde=False) #繪制直方圖

 

 

sns.distplot(x, bins = 20, kde = False) #通過bins可以改變條的數目

 

 

x = np.random.gamma(6, size = 200)

sns.distplot(x, kde = False, fit = stats.gamma) #通過fit進行擬合

 

 

根據均值和協方差生成數據

#生成兩個變量是DateFrame格式的
mean, cov = [0, 1], [(1, 0.5), (0.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)

df = pd.DataFrame(data, columns=["x", "y"])

df

 

 

觀測兩個變量之間的分布關系最好用散點圖

sns.jointplot(x="x", y ="y", data=df);

 

x, y = np.random.multivariate_normal(mean, cov, 1000).T

with sns.axes_style("white"):
    sns.jointplot(x=x, y=y, kind="hex", color='k')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM