1. 程式人生 > >Python圖表分布數據可視化:Seaborn

Python圖表分布數據可視化:Seaborn

pair fill orb pearson () false res 容易 size

conda install seaborn 是安裝到jupyter那個環境的

1. 整體風格設置

對圖表整體顏色、比例等進行風格設置,包括顏色色板等
調用系統風格進行數據可視化

set() / set_style() / axes_style() / despine() / set_context()

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

技術分享圖片

1.1 set()

sns.set() #設置風格之後就會固定住,唯一辦法就是刷新重新設置下
sinplot()
plt.grid(linestyle = --)

技術分享圖片

1.2 set_style()

# 2、set_style()
# 切換seaborn圖表風格
# 風格選擇包括:"white", "dark", "whitegrid", "darkgrid", "ticks"
fig = plt.figure(figsize=(6,6)) ax1 = fig.add_subplot(2,1,1) sns.set_style("whitegrid") data = np.random.normal(size=(20, 6)) + np.arange(6) / 2 sns.boxplot(data=data) plt.title(style - whitegrid) # 仍然可以使用matplotlib的參數 ax2 = fig.add_subplot(2,1,2) #sns.set_style("dark")
sinplot() # 子圖顯示

技術分享圖片

技術分享圖片

1.3 despine()

# 3、despine()
# 設置圖表坐標軸
# seaborn.despine(fig=None, ax=None, top=True, right=True, left=False, 
# bottom=False, offset=None, trim=False)

sns.set_style("ticks")
# 設置風格

fig = plt.figure(figsize=(6,9))
plt.subplots_adjust(hspace=0.3)
# 創建圖表

ax1 = fig.add_subplot(3,1,1)  
sinplot()
sns.despine()
# 刪除了上、右坐標軸

ax2 = fig.add_subplot(3,1,2)
sns.violinplot(data=data) #小提琴圖
# sns.despine(offset=10, trim=True)  #offset坐標軸會偏移10; trim=False是坐標軸沒有限制 
# offset:與坐標軸之間的偏移
# trim:為True時,將坐標軸限制在數據最大最小值

ax3 = fig.add_subplot(3,1,3)
sns.boxplot(data=data, palette="deep")
sns.despine(left=True, right = False) #left=True是左邊不顯示;right=False是顯示
# top, right, left, bottom:布爾型,為True時不顯示

技術分享圖片

技術分享圖片

技術分享圖片

1.4 axes_style()

# 4、axes_style()
# 設置局部圖表風格,可學習和with配合的用法

with sns.axes_style("darkgrid"):
    plt.subplot(211)
    sinplot()
# 設置局部圖表風格,用with做代碼塊區分

sns.set_style("whitegrid")
plt.subplot(212)
sinplot()
# 外部表格風格

技術分享圖片

1.5 set_context()

# 5、set_context()
# 設置顯示比例尺度
# 選擇包括:‘paper‘, ‘notebook‘, ‘talk‘, ‘poster‘

sns.set_context("paper")
sinplot()
# 默認為notebook

技術分享圖片

2. 調色盤

# 對圖表整體顏色、比例等進行風格設置,包括顏色色板等
# 調用系統風格進行數據可視化

# color_palette()

2.1 color_palette()

# 1、color_palette()
# 默認6種顏色:deep, muted, pastel, bright, dark, colorblind
# seaborn.color_palette(palette=None, n_colors=None, desat=None)
current_palette = sns.color_palette()
sns.palplot(current_palette)

技術分享圖片

# 一、其他顏色風格
# 風格內容:Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, 
# BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, 
# Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples,
# Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, 
# Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, 
# autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, 
# cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, 
# gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, 
# hsv_r, icefire, icefire_r, inferno, inferno_r, jet, jet_r, magma, magma_r, mako, mako_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, 
# pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, rocket, rocket_r, seismic, seismic_r, spectral, spectral_r, spring, 
# spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, vlag, vlag_r, winter, winter_r
sns.palplot(sns.color_palette("inferno_r", 8))
# 這裏顏色風格為 hls
# 顏色色塊個數為8個
# 風格顏色反轉(不是所有顏色都可以反轉):Blues/Blues_r

技術分享圖片

#分組顏色設置 - “Paired”
sns.palplot(sns.color_palette("Paired", 10)) #color_palette默認顏色

技術分享圖片

2.2 亮度、飽和度

# 2、設置亮度,飽和度
# 可用方法:
# ① husl_palette([n_colors, h, s, l])
# ② hls_palette([n_colors, h, l, s])
sns.palplot(sns.hls_palette(8, l=.3, s=.9)) #l--> 亮度;s--> 飽和度

技術分享圖片

2.3 cubehelix_palette()

# 3、cubehelix_palette()
# 按照線性增長計算,設置顏色

sns.palplot(sns.cubehelix_palette(8, gamma=2)) #gamma值越大越暗
sns.palplot(sns.cubehelix_palette(8, start=.5, rot=-.75)) #8個色帶,從1.2顏色開始算,rot是旋轉角度;start、rot起始終止顏色
sns.palplot(sns.cubehelix_palette(8, start=2, rot=0, dark=0, light=.95, reverse=True))
# n_colors → 顏色個數
# start → 值區間在0-3,開始顏色
# rot → 顏色旋轉角度
# gamma → 顏色伽馬值,越大顏色越暗
# dark,light → 值區間0-1,顏色深淺
# reverse → 布爾值,默認為False,由淺到深

技術分享圖片

2.4 dark_palette()

 #4、dark_palette(color[, n_colors, reverse, ...]) / light_palette(color[, n_colors, reverse, ...])
# 顏色深淺

sns.palplot(sns.light_palette("green"))   # 按照green做淺色調色盤
#sns.palplot(sns.color_palette("Greens"))  # cmap為Greens風格

sns.palplot(sns.dark_palette("red", reverse=True))   # 按照blue做深色調色盤
# reverse → 轉制顏色

技術分享圖片

2.5 diverging_palette()

# 5、diverging_palette()
# 創建分散顏色
# seaborn.diverging_palette(h_neg, h_pos, s=75, l=50, sep=10, n=6, 
# center=‘light‘, as_cmap=False)¶

sns.palplot(sns.diverging_palette(145, 280, s=85, l=25, n=7)) #第一個起始值和末尾顏色值,s和l是飽和度、亮度,n個數
# h_neg, h_pos → 起始/終止顏色值
# s → 值區間0-100,飽和度
# l → 值區間0-100,亮度
# n → 顏色個數
# center → 中心顏色為淺色還是深色“light”,“dark”,默認為light

技術分享圖片

# 5、diverging_palette()
# 創建分散顏色

plt.figure(figsize = (8,6))
x = np.arange(25).reshape(5, 5) #二維的組
cmap = sns.diverging_palette(200, 20, sep=20, as_cmap=True) #調色盤
sns.heatmap(x, cmap=cmap)#創建熱力圖它就顯示成熱力圖的效果了

技術分享圖片

# 設置調色板後,繪圖創建圖表 

sns.set_style("whitegrid")
# 設置風格

with sns.color_palette("PuBuGn_d"): #設置調色盤
    plt.subplot(211)
    sinplot()

sns.set_palette("husl") #或者這樣
plt.subplot(212)
sinplot()
# 繪制系列顏色

技術分享圖片

3. 分布數據可視化 - 直方圖與密度圖

distplot() / kdeplot() / rugplot()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
% matplotlib inline

sns.set_style("darkgrid")
sns.set_context("paper")
# 設置風格、尺度

import warnings
warnings.filterwarnings(ignore) 
# 不發出警告
rs = np.random.RandomState(10)  # 設定隨機數種子
s = pd.Series(rs.randn(100) * 100)
sns.distplot(s,bins = 10,hist = True,kde = False,norm_hist=False,
            rug = True,vertical = False,
            color = y,label = distplot,axlabel = x)
plt.legend()
# bins → 箱數
# hist、ked → 是否顯示箱數/顯示密度曲線
# norm_hist → 直方圖是否按照密度來顯示
# rug → 是否顯示數據分布情況
# vertical → 是否水平顯示
# color → 設置顏色
# label → 圖例
# axlabel → x軸標註

技術分享圖片

# 1、直方圖 - distplot()
# 顏色詳細設置

sns.distplot(s,rug = True, 
            rug_kws = {color:g} ,   
            # 設置數據頻率分布顏色
            kde_kws={"color": "k", "lw": 1, "label": "KDE",linestyle:--},   
            # 設置密度曲線顏色,線寬,標註、線形
            hist_kws={"histtype": "step", "linewidth": 1,"alpha": 1, "color": "g"})  
            # 設置箱子的風格、線寬、透明度、顏色
            # 風格包括:‘bar‘, ‘barstacked‘, ‘step‘, ‘stepfilled‘

技術分享圖片

# 2、密度圖 - kdeplot()
# 單個樣本數據密度分布圖

sns.kdeplot(s,
           shade = False,  # 是否填充
           color = r,   # 設置顏色
           vertical = False  # 設置是否水平
           )

sns.kdeplot(s,bw=5, label="bw: 0.2",
            linestyle = -,linewidth = 1.2,alpha = 0.5)
sns.kdeplot(s,bw=20, label="bw: 2",
            linestyle = -,linewidth = 1.2,alpha = 0.5)
# bw → 控制擬合的程度,類似直方圖的箱數,設置的數量越大越平滑,越小越容易過度擬合

sns.rugplot(s,height = 0.1,color = k,alpha = 0.5)
# 數據頻率分布圖

技術分享圖片

# 2、密度圖 - kdeplot()
# 兩個樣本數據密度分布圖

rs = np.random.RandomState(2)  # 設定隨機數種子
df = pd.DataFrame(rs.randn(100,2),
                 columns = [A,B])
sns.kdeplot(df[A],df[B], #兩個樣本的數據密度圖
           cbar = True,    # 是否顯示顏色圖例
           shade = True,   # 是否填充
           cmap = Reds,  # 設置調色盤
           shade_lowest=False,  # 最外圍顏色是否顯示
           n_levels = 10   # 曲線個數(如果非常多,則會越平滑)
           )
# 兩個維度數據生成曲線密度圖,以顏色作為密度衰減顯示
plt.grid(linestyle = --)
plt.scatter(df[A], df[B], s=5, alpha = 0.5, color = k) #散點

sns.rugplot(df[A], color="g", axis=x,alpha = 0.5)
sns.rugplot(df[B], color="r", axis=y,alpha = 0.5)
# 註意設置x,y軸

技術分享圖片

# 2、密度圖 - kdeplot()
# 兩個樣本數據密度分布圖
# 多個密度圖

rs1 = np.random.RandomState(2)  
rs2 = np.random.RandomState(5)  
df1 = pd.DataFrame(rs1.randn(100,2)+2,columns = [A,B])
df2 = pd.DataFrame(rs2.randn(100,2)-2,columns = [A,B])
# 創建數據

sns.kdeplot(df1[A],df1[B],cmap = Greens,
            shade = True,shade_lowest=False)
sns.kdeplot(df2[A],df2[B],cmap = Blues,
            shade = True,shade_lowest=False)
# 創建圖表

技術分享圖片

4. 分布數據可視化 - 散點圖

分布數據可視化 - 散點圖

jointplot() / pairplot()

綜合和矩陣散點圖

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
% matplotlib inline

sns.set_style("whitegrid")
sns.set_context("paper")
# 設置風格、尺度

import warnings
warnings.filterwarnings(ignore) 
# 不發出警告
# 1、綜合散點圖 - jointplot()
# 散點圖 + 分布圖

rs = np.random.RandomState(2)  
df = pd.DataFrame(rs.randn(200,2),columns = [A,B])
# 創建數據

sns.jointplot(x=df[A], y=df[B],  # 設置xy軸,顯示columns名稱
              data=df,   # 設置數據
              color = k,   # 設置顏色
              s = 50, edgecolor="w",linewidth=1,  # 設置散點大小、邊緣線顏色及寬度(只針對scatter)
              kind = scatter,   # 設置類型:“scatter”、“reg”、“resid”、“kde”、“hex”
              space = 0.2,  # 設置散點圖和布局圖的間距
              size = 5,   # 圖表大小(自動調整為正方形)
              ratio = 4,  # 散點圖與布局圖高度比,整型
              marginal_kws=dict(bins=15, rug=True)  # 設置柱狀圖箱數,是否設置rug
              )  

技術分享圖片

# 1、綜合散點圖 - jointplot()
# 散點圖 + 分布圖
# 六邊形圖

df = pd.DataFrame(rs.randn(500,2),columns = [A,B])
# 創建數據

with sns.axes_style("white"):
    sns.jointplot(x=df[A], y=df[B],data = df, kind="hex", color="k",
                 marginal_kws=dict(bins=20))

技術分享圖片

# 1、綜合散點圖 - jointplot()
# 散點圖 + 分布圖
# 密度圖

rs = np.random.RandomState(15)
df = pd.DataFrame(rs.randn(300,2),columns = [A,B])
# 創建數據

g = sns.jointplot(x=df[A], y=df[B],data = df,
                  kind="kde", color="k",
                  shade_lowest=False) #是否對外圍做面積的覆蓋
# 創建密度圖

g.plot_joint(plt.scatter,c="w", s=30, linewidth=1, marker="+")
# 添加散點圖

技術分享圖片

# 1、綜合散點圖 - JointGrid()
# 可拆分繪制的散點圖
# plot_joint() + ax_marg_x.hist() + ax_marg_y.hist()

sns.set_style("white")
# 設置風格

tips = sns.load_dataset("tips")
print(tips.head())
# 導入數據

g = sns.JointGrid(x="total_bill", y="tip", data=tips)
# 創建一個繪圖表格區域,設置好x、y對應數據

g.plot_joint(plt.scatter, color =m, edgecolor = white)  # 設置框內圖表,scatter,首先設置個內部的點圖
g.ax_marg_x.hist(tips["total_bill"], color="b", alpha=.6,
                 bins=np.arange(0, 60, 3))            # 設置x軸直方圖,註意bins是數組
g.ax_marg_y.hist(tips["tip"], color="r", alpha=.6,
                 orientation="horizontal",
                 bins=np.arange(0, 12, 1))            # 設置x軸直方圖,註意需要orientation參數

from scipy import stats
g.annotate(stats.pearsonr)    
# 設置標註,可以為pearsonr,spearmanr

plt.grid(linestyle = --)

技術分享圖片

技術分享圖片

# 1、綜合散點圖 - JointGrid()
# 可拆分繪制的散點圖
# plot_joint() + plot_marginals()

g = sns.JointGrid(x="total_bill", y="tip", data=tips)
# 創建一個繪圖表格區域,設置好x、y對應數據

g = g.plot_joint(plt.scatter,color="g", s=40, edgecolor="white")   # 繪制散點圖
plt.grid(linestyle = --)

g.plot_marginals(sns.distplot, kde=True, color="g")                # 繪制x,y軸直方圖

技術分享圖片

# 1、綜合散點圖 - JointGrid()
# 可拆分繪制的散點圖
# plot_joint() + plot_marginals()
# kde - 密度圖

g = sns.JointGrid(x="total_bill", y="tip", data=tips)
# 創建一個繪圖表格區域,設置好x、y對應數據

g = g.plot_joint(sns.kdeplot,cmap = Reds_r)             # 繪制密度圖
plt.grid(linestyle = --)

g.plot_marginals(sns.kdeplot, shade = True, color="r")  # 繪制x,y軸密度圖

技術分享圖片

# 2、矩陣散點圖 - pairplot()

sns.set_style("white")
# 設置風格

iris = sns.load_dataset("iris")
print(iris.head())
# 讀取數據

sns.pairplot(iris,
            kind = scatter,  # 散點圖/回歸分布圖 {‘scatter’, ‘reg’}  
            diag_kind="hist",  # 直方圖/密度圖 {‘hist’, ‘kde’}
            hue="species",   # 按照某一字段進行分類
            palette="husl",  # 設置調色板
            markers=["o", "s", "D"],  # 設置不同系列的點樣式(這裏根據參考分類個數)
            size = 1,   # 圖表大小
            )

技術分享圖片

技術分享圖片

# 2、矩陣散點圖 - pairplot()
# 只提取局部變量進行對比

sns.pairplot(iris,vars=["sepal_width", "sepal_length"],
             kind = reg, diag_kind="kde", 
             hue="species", palette="husl")

技術分享圖片

# 2、矩陣散點圖 - pairplot()
# 其他參數設置

sns.pairplot(iris, diag_kind="kde", markers="+",
             plot_kws=dict(s=50, edgecolor="b", linewidth=1),
             # 設置點樣式
             diag_kws=dict(shade=True)
             # 設置密度圖樣式
            )

技術分享圖片

# 2、矩陣散點圖 - PairGrid()
# 可拆分繪制的散點圖
# map_diag() + map_offdiag()

g = sns.PairGrid(iris,hue="species",palette = hls,
                vars = [sepal_length,sepal_width,petal_length,petal_width],  # 可篩選
                )
# 創建一個繪圖表格區域,設置好x、y對應數據,按照species分類

g.map_diag(plt.hist, 
           histtype = barstacked,   # 可選:‘bar‘, ‘barstacked‘, ‘step‘, ‘stepfilled‘
           linewidth = 1, edgecolor = w)           
# 對角線圖表,plt.hist/sns.kdeplot

g.map_offdiag(plt.scatter,
              edgecolor="w", s=40,linewidth = 1,   # 設置點顏色、大小、描邊寬度
             )     
# 其他圖表,plt.scatter/plt.bar...

g.add_legend()
# 添加圖例

技術分享圖片

# 2、矩陣散點圖 - PairGrid()
# 可拆分繪制的散點圖
# map_diag() + map_lower() + map_upper()

g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot, lw=3)   # 設置對角線圖表
g.map_upper(plt.scatter, color = r)     # 設置對角線上端圖表
g.map_lower(sns.kdeplot, cmap="Blues_d")      # 設置對角線下端圖表

技術分享圖片

Python圖表分布數據可視化:Seaborn