半小時拿下Python數據處理之Seaborn篇


Seaborn簡介

Seaborn是一種基於matplotlib的圖形可視化python庫。它提供了一種高度交互式界面,便於用戶能夠做出各種有吸引力的統計圖表。Seaborn其實是在matplotlib的基礎上進行了更高級的API封裝,從而使得作圖更加容易,在大多數情況下使用Seaborn就能做出很具有吸引力的圖,而使用matplotlib就能製作具有更多特色的圖。應該把Seaborn視爲matplotlib的補充,而不是替代物。同時它能高度兼容numpypandas數據結構以及scipystatsmodels等統計模式。掌握Seaborn能很大程度幫助我們更高效的觀察數據與圖表,並且更加深入瞭解它們。

其有如下特點:

  • 基於matplotlib aesthetics繪圖風格,增加了一些繪圖模式
  • 增加調色板功能,利用色彩豐富的圖像揭示您數據中的模式
  • 運用數據子集繪製與比較單變量和雙變量分佈的功能
  • 運用聚類算法可視化矩陣數據
  • 靈活運用處理時間序列數據
  • 利用網格建立複雜圖像集

Seaborn樣式

matplotlib與seaborn繪圖比較

import seaborn as sns
import numpy as np
import matplotlib as mpl
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 * .5) * (7 - i) * flip)
sinplot() #採用matplotlib繪製

sns.set() #採用seaborn默認設置
sinplot()

Seaborn 5種主題風格

  • darkgrid
  • whitegrid
  • dark
  • white
  • ticks
sns.set_style("darkgrid")
sinplot()

sns.set_style("whitegrid")
sinplot()

sns.set_style("dark")
sinplot()

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-agcVbXkK-1589899017301)(http://image.yigouai.cn/pandas_output_13_0.png)]

sns.set_style("white")
sinplot()

sns.set_style("ticks")
sinplot()

用despine()移除軸線

樣式whiteticks都可以通過去除上方和右方不必要的軸線來得到改善. 而這些是不可能在matplotlib裏設置參數做到的,但是你可以調用seaborn的函數despine()來去除軸線:

sns.set_style("ticks")
sinplot()
sns.despine() # 去除上面與右面軸線

有些佈局也可以通過調整軸線距數據的偏移來改善,這也能在despine()裏完成.當ticks不能覆蓋軸線的整個範圍時,trim參數可以限制顯示的軸線的範圍.

data = np.random.normal(size=(20, 6)) + np.arange(6) / 2 # (20, 6) 二維數據
f, ax = plt.subplots()
sns.violinplot(data) # 琴形圖
sns.despine(offset=10,trim=True)

你也可能通過設置另外的參數來控制移除哪條軸線:

sns.set_style("whitegrid")
sns.boxplot(data=data, palette="deep") #箱型圖
sns.despine(left=True) #去除左邊的軸線

臨時設置圖表樣式

儘管來回切換樣式是很簡單的,但是你也可以在with語句裏用axes_style()函數來臨時設置控制佈局的參數.這也允許你用不同的風格來製作圖表,這是一種常見的編程模式,使得控制樣式和風格能夠多變。

with sns.axes_style("darkgrid"):
    plt.subplot(211)
    sinplot()
plt.subplot(212)
sinplot(-1)

重載seaborn樣式的元素

如果你想要自定義seaborn的樣式,你可以用詞典(dictionary)將一系列控制參數賦值給axes_style()函數和set_style()函數的rc參數裏. 注意你只能通過這種方式重載樣式定義的部分.(但是,更高級的set()函數可以處理包含任意matplotlib參數的詞典)

如果你想要知道都包含了哪些參數,你可以調用沒有參數的函數,它會返回當前設置:

sns.axes_style()
{'axes.axisbelow': True,
 'axes.edgecolor': '.8',
 'axes.facecolor': 'white',
 'axes.grid': True,
 'axes.labelcolor': '.15',
 'axes.linewidth': 1.0,
 'figure.facecolor': 'white',
 'font.family': ['sans-serif'],
 'font.sans-serif': ['Arial',
  'DejaVu Sans',
  'Liberation Sans',
  'Bitstream Vera Sans',
  'sans-serif'],
 'grid.color': '.8',
 'grid.linestyle': '-',
 'image.cmap': 'rocket',
 'legend.frameon': False,
 'legend.numpoints': 1,
 'legend.scatterpoints': 1,
 'lines.solid_capstyle': 'round',
 'text.color': '.15',
 'xtick.color': '.15',
 'xtick.direction': 'out',
 'xtick.major.size': 0.0,
 'xtick.minor.size': 0.0,
 'ytick.color': '.15',
 'ytick.direction': 'out',
 'ytick.major.size': 0.0,
 'ytick.minor.size': 0.0}

然後你可以設置這些參數的不同版本:

sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()

使用plotting_context()set_context()設置佈局元素的規模

佈局元素的規模被獨立的參數集合控制,這能讓你使用相同的代碼得到不同大小的規模合適的佈局

首先讓我們重新調用set()函數得到缺省設置:

sns.set()

有4種預設好的上下文(context),按相對大小排序分別是:paper, notebook, talk,和poster.缺省的規模是notebook,上述的所有圖表都是它.

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()

大部分你現在所稽首的樣式函數都應該被轉換成上下文函數.

你可以調用set_context(),將上下文的名字當作一個參數傳入,然後你就可以通過提供一個寫有各項設置值的詞典重載上下文的參數。

在修改上下文時,你也可以單獨修改字體大小。(更高級的set()裏也可以這麼做)

sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sinplot()

Seaborn配色方案

配色是圖表設計裏最重要的方面之一,因爲如果配色方案好,它可以清晰展現數據的模式和規律,否則就會把這些規律和模式隱藏起來。
Seaborn讓選擇和使用配色方案變得簡單且適用於你工作的數據種類和你想要達到的可視化目標。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set(rc={"figure.figsize": (6, 6)})

調色板

  • 顏色很重要
  • color_palette()能傳入任何Matplotlib所支持的顏色
  • color_palette()不寫參數則默認顏色
  • set_palette()設置所有圖的顏色

分類色板

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))#按照生成的顏色對應不同的分類
<matplotlib.axes._subplots.AxesSubplot at 0x1a1f2bc978>

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

  • l-亮度 lightness
  • s-飽和 saturation
sns.palplot(sns.hls_palette(8, l=.7, s=.9))

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-rNOmDHMZ-1589899017365)(http://image.yigouai.cn/pandas_output_47_0.png)]

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

使用xkcd顏色自定義調色板

xkcd包含了一套衆包努力的針對隨機RGB色的命名。產生了954個可以隨時通過xdcd_rgb字典中調用的命名顏色。
可以通過sns.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)
[<matplotlib.lines.Line2D at 0x1a1f3264e0>]

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=1.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)) #漸變翻轉

#應用調色板
data = np.random.normal(size=(20, 8)) + np.arange(8) / 2  #生成數據
sns.boxplot(data=data,palette=sns.cubehelix_palette(8, start=.5, rot=-.75))#按照生成的顏色對應不同的分類
<matplotlib.axes._subplots.AxesSubplot at 0x1a1f1c59b0>

Seaborn變量分析繪圖

%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats, integrate
import matplotlib.pyplot as plt

import seaborn as sns
sns.set(color_codes=True)
np.random.seed(sum(map(ord, "distributions")))

使用sns.distplot()函數畫直方圖

x = np.random.normal(size=100)
sns.distplot(x,kde=False) #distplot()函數會根據輸入數據自動繪製直方圖
<matplotlib.axes._subplots.AxesSubplot at 0x1a1fb2a240>

你也可以通過bins自己劃分直方圖的切分粒度

sns.distplot(x, bins=20, kde=False)
<matplotlib.axes._subplots.AxesSubplot at 0x1a202ebdd8>

通過fit查看數據分佈的情況

x = np.random.gamma(6, size=200)
sns.distplot(x, kde=False, fit=stats.gamma)
<matplotlib.axes._subplots.AxesSubplot at 0x1a204df5f8>

使用jointplot()函數繪製散點圖

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

#生成數據
mean, cov = [0, 1], [(1, .5), (.5, 1)] #自定義均值與協方差
data = np.random.multivariate_normal(mean, cov, 200) #生成200個數據
df = pd.DataFrame(data, columns=["x", "y"]) #通過pandas讀入數據
print(df.head())
          x         y
0  0.585042  1.162682
1  0.722117  2.141580
2  0.120990  0.498821
3 -0.795773  2.085261
4 -0.614260  2.215906
sns.jointplot(x="x", y="y", data=df)
<seaborn.axisgrid.JointGrid at 0x1a206a5b00>

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-CiJthrnE-1589899017442)(http://image.yigouai.cn/pandas_output_75_1.png)]

通過kind="hex"使散點圖具備透視性,更加容易查看數據的散點分佈密度情況

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")

使用pairplot()函數繪製關係圖

兩不同變量比較繪製散點圖,變量自身比較繪製直方圖

iris = sns.load_dataset("iris") #載入鳶尾花數據集
sns.pairplot(iris) #繪製
<seaborn.axisgrid.PairGrid at 0x1a20ef4588>

Seaborn迴歸分析繪圖

%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數據集

tips.head() #查看數據集

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

regplot()繪製迴歸關係圖

#採用regplot繪製擬合的數據線
sns.regplot(x="total_bill", y="tip", data=tips) #x軸代表花的錢的數據,y軸對應給小費的數據
<matplotlib.axes._subplots.AxesSubplot at 0x22d8d8db518>

lmplot()繪製迴歸關係圖

lmplot是一種集合基礎繪圖與基於數據建立迴歸模型的繪圖方法。旨在創建一個方便擬合數據集迴歸模型的繪圖方法,利用huecolrow參數來控制繪圖變量。

seaborn.lmplot(x, y, data, hue=None, col=None, row=None, palette=None, col_wrap=None, size=5, aspect=1, markers='o', sharex=True, sharey=True, hue_order=None, col_order=None, row_order=None, legend=True, legend_out=True, x_estimator=None, x_bins=None, x_ci='ci', scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, order=1, logistic=False, lowess=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=False, x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None)

參數說明:

  • hue, col, row : strings #定義數據子集的變量,並在不同的圖像子集中繪製
  • size : scalar, optional #定義子圖的高度
  • markers : matplotlib marker code or list of marker codes, optional #定義散點的圖標
  • col_wrap : int, optional #設置每行子圖數量
  • order : int, optional #多項式迴歸,設定指數
  • logistic : bool, optional #邏輯迴歸
  • logx : bool, optional #轉化爲log(x)
#研究小費tips與總消費金額total_bill在吸菸與不吸菸人之間的關係
g = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips,palette="Set1")

#研究在不同星期下,消費總額與消費的迴歸關係
# col|hue控制子圖不同的變量day,col_wrap控制每行子圖數量,size控制子圖高度
g = sns.lmplot(x="total_bill", y="tip", col="day", hue="day",data=tips, col_wrap=2, size=3)

pokemon=pd.read_csv('../dataset/Pokemon.csv') #載入寵物小精靈戰鬥力數據集
pokemon.head()

# Name Type 1 Type 2 Total HP Attack Defense Sp. Atk Sp. Def Speed Generation Legendary
0 1 Bulbasaur Grass Poison 318 45 49 49 65 65 45 1 False
1 2 Ivysaur Grass Poison 405 60 62 63 80 80 60 1 False
2 3 Venusaur Grass Poison 525 80 82 83 100 100 80 1 False
3 3 VenusaurMega Venusaur Grass Poison 625 80 100 123 122 120 80 1 False
4 4 Charmander Fire NaN 309 39 52 43 60 50 65 1 False

#觀察每一代攻擊與防禦的分佈,利用二次多項式逼近
sns.lmplot(x="Defense", y="Attack",data=pokemon,col="Generation", hue="Generation",col_wrap=3, size=3,order=2)
<seaborn.axisgrid.FacetGrid at 0x22d8bce32e8>

#繼續在同一圖中觀察不同代的sp.Atk,Sp.Def線性關係
sns.lmplot(x="Sp. Atk", y="Sp. Def", data=pokemon, hue='Generation', size=5,order=1)
<seaborn.axisgrid.FacetGrid at 0x22d8be4b5f8>

Seaborn分類分析繪圖

%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(style="whitegrid", color_codes=True)
np.random.seed(sum(map(ord, "categorical")))
titanic = sns.load_dataset("titanic") #導入泰坦尼克數據集
tips = sns.load_dataset("tips") #導入小費數據集
iris = sns.load_dataset("iris") #導入鳶尾花數據集

散點圖

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

問題:有重疊,無法看見數據的密度

  • 解決方法一:通過jitter抖動

抖動是平時可視化中的常用的觀察“密度”的方法,除了使用參數抖動,特定的抖動需求也可以用numpy在數據上處理實現

sns.stripplot(x="day", y="total_bill", data=tips, jitter=True) # jitter抖動
<matplotlib.axes._subplots.AxesSubplot at 0x22d8a3216a0>

  • 解決方法二:通過swarmplot()函數
sns.swarmplot(x="day", y="total_bill", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x22d87f3b128>

sns.swarmplot(x="day", y="total_bill", hue="sex",data=tips) #hue 參數控制分組繪圖
<matplotlib.axes._subplots.AxesSubplot at 0x22d8a428860>

箱型圖

箱形圖(Box-plot)又稱爲盒須圖、盒式圖或箱線圖,是一種用作顯示一組數據分散情況資料的統計圖。因形狀如箱子而得名。

如上圖所示,標示了圖中每條線表示的含義,其中應用到了分位值(數)的概念。
主要包含六個數據節點,將一組數據從大到小排列,分別計算出他的上邊緣,上四分位數Q3,中位數,下四分位數Q1,下邊緣,還有一個異常值。

舉例說明,以下是箱形圖的具體例子:

這組數據顯示出:

  • 最小值(minimum)=5
  • 下四分位數(Q1)=7
  • 中位數(Med–也就是Q2)=8.5
  • 上四分位數(Q3)=9
  • 最大值(maximum)=10
  • 平均值=8
  • 四分位間距=Q3-Q1=2 (即ΔQ)
  • 最大值區間: Q3+1.5ΔQ = 12
  • 最小值區間: Q1-1.5ΔQ = 4
  • mild outlier = 3.5
  • extreme outlier = 0.5
sns.boxplot(x="day", y="total_bill", hue="time", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x22d8bbd7240>

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-EoGJB6ZG-1589899017501)(http://image.yigouai.cn/pandas_output_108_1.png)]

琴形圖

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, orient=None, linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)
  • split: bool, optional #琴形圖是否從中間分開兩部分
  • scale: {“area”, “count”, “width”}, optional #用於調整琴形圖的寬帶。
    • area——每個琴圖擁有相同的面域;
    • count——根據樣本數量來調節寬度;
    • width——每個琴圖則擁有相同的寬度。
  • inner: {“box”, “quartile”, “point”, “stick”, None}, optional #控制琴圖內部數據點的形態。
    • box——繪製微型 boxplot;
    • quartiles——繪製四分位的分佈;
    • point/stick——繪製點或小豎條。
sns.violinplot(x="total_bill", y="day", hue="time", data=tips)
<matplotlib.axes._subplots.AxesSubplot at 0x22d8a9f97b8>

sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True) #split: bool, optional #琴形圖是否從中間分開兩部分

條形圖

顯示值的集中趨勢可以用條形圖

sns.barplot(x="sex", y="survived", hue="class", data=titanic)
<matplotlib.axes._subplots.AxesSubplot at 0x22d8a5bc358>

點圖

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

sns.pointplot(x="sex", y="survived", hue="class", data=titanic)
<matplotlib.axes._subplots.AxesSubplot at 0x22d8a5bcda0>

#詳細指定屬性值
sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
              palette={"male": "g", "female": "m"}, #  指定顏色
              markers=["^", "o"],  # 指定點樣式
              linestyles=["-", "--"]); # 指定線型樣式

組合

#琴型圖 + 分散點圖
sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5)
<matplotlib.axes._subplots.AxesSubplot at 0x22d8a3f4908>

多層面板分類圖

factorplot()函數是對各種圖形的一個更高級別的API封裝,在Seaborn中非常常用。

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)

參數說明:

  • 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)
  • facet_kws FacetGrid的其他參數 (字典)
sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips) #默認是點圖
<seaborn.axisgrid.FacetGrid at 0x22d8a79def0>

sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar") #繪製條形圖
<seaborn.axisgrid.FacetGrid at 0x22d8a648748>

sns.factorplot(x="day", y="total_bill", hue="smoker",
               col="time", data=tips, kind="swarm") #繪製分散點圖
<seaborn.axisgrid.FacetGrid at 0x22d8a867be0>

sns.factorplot(x="time", y="total_bill", hue="smoker",
               col="day", data=tips, kind="box", size=4, aspect=.5) #繪製箱型圖
<seaborn.axisgrid.FacetGrid at 0x22d8a8bcb00>

Seaborn熱圖繪製

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

熱圖基礎

seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annotkws=None, linewidths=0, linecolor='white', cbar=True, cbarkws=None, cbar_ax=None, square=False, ax=None, xticklabels=True, yticklabels=True, mask=None, **kwargs)
  • data:矩陣數據集,可以使numpy的數組(array),如果是pandas的dataframe,則df的index/column信息會分別對應到heatmap的columns和rows
  • linewidths,熱力圖矩陣之間的間隔大小
  • vmax,vmin, 圖例中最大值和最小值的顯示值,沒有該參數時默認不顯示
  • cmap:matplotlib的colormap名稱或顏色對象;如果沒有提供,默認爲cubehelix map (數據集爲連續數據集時) 或 RdBu_r (數據集爲離散數據集時)
  • center:將數據設置爲圖例中的均值數據,即圖例中心的數據值;通過設置center值,可以調整生成的圖像顏色的整體深淺;設置center數據時,如果有數據溢出,則手動設置的vmax、vmin會自動改變
  • xticklabels: 如果是True,則繪製dataframe的列名。如果是False,則不繪製列名。如果是列表,則繪製列表中的內容作爲xticklabels。 如果是整數n,則繪製列名,但每個n繪製一個label。 默認爲True。
  • yticklabels: 如果是True,則繪製dataframe的行名。如果是False,則不繪製行名。如果是列表,則繪製列表中的內容作爲yticklabels。 如果是整數n,則繪製列名,但每個n繪製一個label。 默認爲True。默認爲True。
  • annotate的縮寫,annot默認爲False,當annot爲True時,在heatmap中每個方格寫入數據
  • annot_kws,當annot爲True時,可設置各個參數,包括大小,顏色,加粗,斜體字等
  • fmt,格式設置
uniform_data = np.random.rand(3, 3) #生成數據
print (uniform_data)
heatmap = sns.heatmap(uniform_data) # 生成熱力圖
[[ 0.64272796  0.0229858   0.21897478]
 [ 0.41076627  0.28860677  0.94805105]
 [ 0.96513582  0.57781451  0.96400349]]

# 改變顏色映射的值範圍
ax = sns.heatmap(uniform_data, vmin=0.2, vmax=1)

#爲以0爲中心的數據繪製一張熱圖
ax = sns.heatmap(uniform_data, center=0)

案例分析

flights = sns.load_dataset("flights") #加載航班數據集
flights.head() #顯示部分數據

year month passengers
0 1949 January 112
1 1949 February 118
2 1949 March 132
3 1949 April 129
4 1949 May 121
flights = flights.pivot("month", "year", "passengers") #修改數據排列
flights.head()

year 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
month
January 112 115 145 171 196 204 242 284 315 340 360 417
February 118 126 150 180 196 188 233 277 301 318 342 391
March 132 141 178 193 236 235 267 317 356 362 406 419
April 129 135 163 181 235 227 269 313 348 348 396 461
May 121 125 172 183 229 234 270 318 355 363 420 472
ax = sns.heatmap(flights) #繪製熱圖

ax = sns.heatmap(flights, annot=True,fmt="d") #在heatmap中每個方格寫入數據,按照整數形式

ax = sns.heatmap(flights, linewidths=.5) #熱力圖矩陣之間的間隔大小

ax = sns.heatmap(flights, cmap="YlGnBu") #修改熱圖顏色

ax = sns.heatmap(flights, cbar=False) #不顯示熱圖圖例

參考

Style functions

Color palettes

Distribution plots

Categorical plots

Regression plots

Axis grid objects

10分鐘python圖表繪製


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章