1. 程式人生 > >人工智慧學習筆記——視覺化庫Seaborn

人工智慧學習筆記——視覺化庫Seaborn

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%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()

sns.set()#使用Seaborn庫的預設引數
sinplot()

5種主題風格

  • darkgrid
  • whitegrid
  • dark
  • white
  • ticks

sns.set_style("whitegrid")
data = np.random.normal(size=(20,6))+np.arange(6)/2
sns.boxplot(data = data)

sns.set_style("dark")
sinplot()

sns.set_style("white")
sinplot()

sns.set_style("ticks")
sinplot()

sns.set_style("ticks")
sinplot()
sns.despine()

sns.despine(offset=20)#設定與座標軸的偏移

sns.set_style("whitegrid")
data = np.random.normal(size=(20,6))+np.arange(6)/2
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)

內容
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=1.5, rc={"lines.linewidth": 2.5})#font_scale字型大小lines.linewidth線寬
sinplot()


調色盤

  • 顏色很重要
  • color_palette()能傳入任何Matplotlib所支援的顏色
  • color_palette()不寫引數則預設顏色
  • set_palette()設定所有圖的顏色

sns.set(rc={"figure.figsize":(6,6)})

current_palette = sns.color_palette()
sns.palplot(current_palette)

6個預設的顏色迴圈主題: deep, muted, pastel, bright, dark, colorblind

圓形畫板
當你有六個以上的分類要區分時,最簡單的方法就是在一個圓形的顏色空間中畫出均勻間隔的顏色(這樣的色調會保持亮度和飽和度不變)。這是大多數的當他們需要使用比當前預設顏色迴圈中設定的顏色更多時的預設方案。
最常用的方法是使用hls的顏色空間,這是RGB值的一個簡單轉換。

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

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=.7, s=.9))

sns.palplot(sns.hls_palette(8, l=.5, s=.9))

顏色對比
sns.palplot(sns.color_palette("Paired",8))

使用xkcd顏色來命名顏色
xkcd包含了一套眾包努力的針對隨機RGB色的命名。產生了954個可以隨時通過xdcd_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)

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=.5, rot=-.75))

sns.palplot(sns.cubehelix_palette(8, start=.75, rot=-.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))

x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T
pal = sns.dark_palette("green", as_cmap=True)
sns.kdeplot(x, y, cmap=pal);

sns.palplot(sns.light_palette((210, 90, 60), input="husl"))

單變數分析繪製

from scipy import stats, integrate
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "distributions")))

繪製直方圖

x = np.random.normal(size=100)
sns.distplot(x,kde=False)#核密度不設定

sns.distplot(x, bins=20, kde=False)

資料分佈情況

x = np.random.gamma(6, size=200)
sns.distplot(x, kde=False, fit=stats.gamma)

根據均值和協方差生成資料

mean, cov = [0, 1], [(1, .5), (.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")

兩兩對比繪圖
iris = sns.load_dataset("iris")
sns.pairplot(iris)

迴歸分析繪圖
%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt

import seaborn as sns
sns.set(color_codes=True)

np.random.seed(sum(map(ord, "regression")))
tips = sns.load_dataset("tips")
tips.head()

regplot()和lmplot()都可以繪製迴歸關係,推薦regplot()
sns.regplot(x = "total_bill",y = "tip",data = tips)

sns.lmplot(x="total_bill", y="tip", data=tips)

sns.regplot(x="size", y="tip", data=tips, x_jitter=.05)#加上0.05的範圍浮動

sns.stripplot(x="day", y="total_bill", data=tips);

重疊是很常見的現象,但是重疊影響我觀察資料的量了
sns.stripplot(x="day", y="total_bill", data=tips, jitter=True)#資料左右偏移

sns.swarmplot(x="day", y="total_bill", data=tips)

sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips)#hue=其統計特徵

盒圖

  • IQR即統計學概念四分位距,第一/四分位與第三/四分位之間的距離
  • N = 1.5IQR 如果一個值>Q3+N或 < Q1-N,則為離群點

sns.boxplot(x="day", y="total_bill", hue="time", data=tips);

sns.boxplot(data=iris,orient="h");

小提琴圖

sns.violinplot(x="total_bill", y="day", hue="time", data=tips);

sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True);

影象合併
sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5)

sns.barplot(x="sex", y="survived", hue="class", data=titanic);#泰坦尼克資料按照不同性別在不同等級的船艙的獲救概率

點圖可以更好的描述變化差異

sns.pointplot(x="sex", y="survived", hue="class", data=titanic);

sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
              palette={"male": "g", "female": "m"},
              markers=["^", "o"], linestyles=["-", "--"]);

多層面板分類圖

sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips)

sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar")

sns.factorplot(x="day", y="total_bill", hue="smoker",
               col="time", data=tips, kind="swarm")#col緯度

sns.factorplot(x="time", y="total_bill", hue="smoker",
               col="day", data=tips, kind="box", size=4, aspect=.5)#size大小,aspect長寬比

seaborn.factorplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=, 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)

Parameters:

  • x,y,hue 資料集變數 變數名
  • date 資料集 資料集名
  • row,col 更多分類變數進行平鋪顯示 變數名
  • col_wrap 每行的最高平鋪數 整數
  • estimator 在每個分類中進行向量到標量的對映 向量
  • ci 置信區間 浮點數或None
  • n_boot 計算置信區間時使用的引導迭代次數 整數
  • units 取樣單元的識別符號,用於執行多級引導和重複測量設計 資料變數或向量資料
  • order, hue_order 對應排序列表 字串列表
  • row_order, col_order 對應排序列表 字串列表
  • kind : 可選:point 預設, bar 柱形圖, count 頻次, box 箱體, violin 提琴, strip 散點,swarm 分散點 size 每個面的高度(英寸) 標量 aspect 縱橫比 標量 orient 方向 "v"/"h" color 顏色 matplotlib顏色 palette 調色盤 seaborn顏色色板或字典 legend hue的資訊面板 True/False legend_out 是否擴充套件圖形,並將資訊框繪製在中心右邊 True/False share{x,y} 共享軸線 True/False

熱度圖繪製

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np; 
np.random.seed(0)
import seaborn as sns;

sns.set()

uniform_data = np.random.rand(3, 3)
print (uniform_data)
heatmap = sns.heatmap(uniform_data)

[[0.5488135  0.71518937 0.60276338]
 [0.54488318 0.4236548  0.64589411]
 [0.43758721 0.891773   0.96366276]]

ax = sns.heatmap(uniform_data, vmin=0.2, vmax=0.5)

normal_data = np.random.randn(3, 3)
print (normal_data)
ax = sns.heatmap(normal_data, center=0)#以0為中心

flights = sns.load_dataset("flights")
flights.head()

flights = flights.pivot("month", "year", "passengers")
print (flights)
ax = sns.heatmap(flights)

year       1949  1950  1951  1952  1953  1954  1955  1956  1957  1958  1959  \
month                                                                         
January     112   115   145   171   196   204   242   284   315   340   360   
February    118   126   150   180   196   188   233   277   301   318   342   
March       132   141   178   193   236   235   267   317   356   362   406   
April       129   135   163   181   235   227   269   313   348   348   396   
May         121   125   172   183   229   234   270   318   355   363   420   
June        135   149   178   218   243   264   315   374   422   435   472   
July        148   170   199   230   264   302   364   413   465   491   548   
August      148   170   199   242   272   293   347   405   467   505   559   
September   136   158   184   209   237   259   312   355   404   404   463   
October     119   133   162   191   211   229   274   306   347   359   407   
November    104   114   146   172   180   203   237   271   305   310   362   
December    118   140   166   194   201   229   278   306   336   337   405   

year       1960  
month            
January     417  
February    391  
March       419  
April       461  
May         472  
June        535  
July        622  
August      606  
September   508  
October     461  
November    390  
December    432 

ax = sns.heatmap(flights, annot=True,fmt="d")

ax = sns.heatmap(flights, linewidths=.5)#間距

ax = sns.heatmap(flights, cmap="YlGnBu")

ax = sns.heatmap(flights, cbar=False)#隱藏bar