seaborn學習筆記(三):直方圖、條形圖、條帶圖


 

1 直方圖與條形圖

在過去很長一段時間,我一直分不清直方圖和條形圖,或者說一直認為兩者是一樣的,直到看到histplot()和barplot()兩個繪圖方法,前者是繪制直方圖,后者是繪制條形圖。通過仔細對比兩者各項功能后,我得出結論,兩者十分相似,但有些許不同:直方圖側重於統計數據在數軸上各個位置的分布情況,統計的對象往往是連續型數值數據的,根據數值的大小分區間進行分組統計,例如有100個學生的身高,需要統計100個學生在各個身高段的分布情況;條形圖不同,條形圖分組往往是針對離散型數據或者說定性的分類數據,例如對比男生的平均身高和女生的平均身高。不知道我這么理解對不對,歡迎留言討論。

 

2 histplot():直方圖

 

主要參數如下:

  • data:繪圖數據,可以是pandas.DataFrame,numpy.ndarray或者字典等
  • x,y:指定的x軸, y軸數據,可以是向量或者字符串,當是字符串時,一定是data中的一個key
  • hue:可以是向量(pandas中的一列,或者是list),也可以是字符串(data中的一個key),seaborn將根據這一列設置不同顏色
  • weights: 數據加權的權重
  • stat: 柱形的統計方式

    1)count:統計每個區間的值的個數

    2)frequency:區間內取值個數除以區間寬度

    3)probability或proportion:進行標准化使條形高度總和為1

    4)percent:標准化使條形總高度為100

    5)使條形總面積為1

  • bins: 字符型、整型、向量都可以,可以是引用規則的名稱、箱子的數量或箱子的分段或者分箱規則名稱,規則名稱見下方示例
  • binwidth: 條形寬度
  • binrange: 條形邊緣的最大值或最小值
  • discrete: 如果為True,則默認為binwidth=1,並繪制條形圖,使其位於相應數據點的中心。這避免了在使用離散(整數)數據時可能出現的“間隙”。
  • cumulative: 布爾型,是否逐個累加每個條形高度進行繪圖
  • multiple: 直接看下文效果吧
  • element: 直接看下文效果吧
  • fill: 條形內部是否填充顏色
  • shrink: 縮小條形的寬度
  • kde: 是否生成核密度曲線
  • color: 設置條形顏色
  • legend: 是否顯示圖例
  • ax: 繪圖的坐標軸實例
In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
In [2]:
penguins = sns.load_dataset('penguins',data_home='.')
In [3]:
penguins.head(2)
Out[3]:
 
  species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex
0 Adelie Torgersen 39.1 18.7 181.0 3750.0 Male
1 Adelie Torgersen 39.5 17.4 186.0 3800.0 Female
 

2.1 為圖像設置標題

histplot()方法返回值為matplotlib.axes._subplots.AxesSubplot類實例,通過實例的set_title()方法可以為圖像添加標題:

In [4]:
pic = sns.histplot(penguins, x="flipper_length_mm")
pic.set_title('flipper_length_mm')
Out[4]:
Text(0.5, 1.0, 'flipper_length_mm')
 
 

2.2 ax:自定義繪圖坐標系

在不傳遞ax參數時,seaborn會自行創建坐標系進行繪圖,我們也可以自己創建坐標系,通過ax參數傳遞,這樣做的好處是可以靈活繪制多個子圖:

In [5]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0])
pic = sns.histplot(penguins, x="body_mass_g", ax=ax[1])
 
 

另外,在histplot()方法中,沒有提供太多關於坐標軸設置的參數,難以對坐標軸進行個性化定制,如果在繪圖前,先創建好坐標軸,即可完成對坐標軸的設置(關於坐標軸的創建和設置,請參考Matplotlib數據可視化(2):三大容器對象與常用設置

In [6]:
ax=plt.axes((0.1, 0.1, 0.8, 0.7), facecolor='green')
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax)
 
 

2.3 x, y:傳遞數據,控制圖形方向

 

x, y參數不能同時傳遞,當傳遞x時,x軸為數據取值范圍,y軸為統計次數;當傳遞y值時,y軸為數據取值范圍,x軸為統計次數:

In [7]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0])
pic.set_title('x')
pic = sns.histplot(penguins, y="flipper_length_mm", ax=ax[1])
pic.set_title('y')
Out[7]:
Text(0.5, 1.0, 'y')
 
 

2.4 stat:y軸顯示數據的方式

In [8]:
fig, ax =plt.subplots(1,5,constrained_layout=True, figsize=(15, 3))
_ = sns.histplot(penguins, x="flipper_length_mm", stat="count", ax=ax[0])      # count, 也是默認值
_ = sns.histplot(penguins, x="flipper_length_mm", stat="frequency", ax=ax[1])  # frequency 
_ = sns.histplot(penguins, x="flipper_length_mm", stat="probability", ax=ax[2])# probability
_ = sns.histplot(penguins, x="flipper_length_mm", stat="percent", ax=ax[3])    # percent
_ = sns.histplot(penguins, x="flipper_length_mm", stat="density", ax=ax[4])    # density
 
 

2.5 bins:指定分箱方式

 

指定分箱個數或者每個條形區間進行繪圖:

In [9]:
fig, ax =plt.subplots(1,3,constrained_layout=True, figsize=(12, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0], bins=5)
pic.set_title('bins=5')
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], bins=10)
pic.set_title('bins=10')
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[2], bins=[150, 175, 200, 225, 250])
pic.set_title('bins=[150, 175, 200, 225, 250]')
Out[9]:
Text(0.5, 1.0, 'bins=[150, 175, 200, 225, 250]')
 
 

也可以指定分箱的規則:

In [10]:
fig, ax =plt.subplots(2,4,constrained_layout=True, figsize=(15, 6))
pic = sns.histplot(penguins, x="flipper_length_mm", bins="auto", ax=ax[0][0])      # count, 也是默認值
pic.set_title('auto')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="fd", ax=ax[0][1])  # frequency 
pic.set_title('fd')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="doane", ax=ax[0][2])# probability
pic.set_title('doane')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="scott", ax=ax[0][3])    # percent
pic.set_title('scott')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="stone", ax=ax[1][0])      # count, 也是默認值
pic.set_title('stone')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="rice", ax=ax[1][1])  # frequency 
pic.set_title('rice')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="sturges", ax=ax[1][2])# probability
pic.set_title('sturges')
pic = sns.histplot(penguins, x="flipper_length_mm", bins="sqrt", ax=ax[1][3])    # percent
pic.set_title('sqrt')
 
D:\ProgramData\Anaconda3\envs\machine_learning\lib\site-packages\numpy\lib\histograms.py:669: RuntimeWarning: The number of bins estimated may be suboptimal.
  bin_edges, _ = _get_bin_edges(a, bins, range, weights)
Out[10]:
Text(0.5, 1.0, 'sqrt')
 
 

2.6 binwidth:設置柱形寬度

In [11]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
_ = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0], binwidth=1)
_ = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], binwidth=3)
 
 

2.7 cumulative:累積每個條形高度進行繪圖

In [12]:
sns.histplot(penguins, x="flipper_length_mm", cumulative=True)
Out[12]:
<AxesSubplot:xlabel='flipper_length_mm', ylabel='Count'>
 
In [13]:
sns.histplot(penguins, x="flipper_length_mm", multiple="layer")
Out[13]:
<AxesSubplot:xlabel='flipper_length_mm', ylabel='Count'>
 
 

2.8 hue:顏色區分條形組成

In [14]:
_ = sns.histplot(penguins, x="flipper_length_mm", hue="species")
 
 

2.9 element

In [15]:
fig, ax =plt.subplots(1,3,constrained_layout=True, figsize=(12, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[0], element="bars")
pic.set_title('element="bars"')
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[1], element="step")
pic.set_title('element="step')
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[2], element="poly")
pic.set_title('element="poly"')
Out[15]:
Text(0.5, 1.0, 'element="poly"')
 
 

2.10 multiple

In [16]:
fig, ax =plt.subplots(1,4,constrained_layout=True, figsize=(16, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[0], multiple="layer")
pic.set_title('multiple="layer"')
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[1], multiple="dodge")
pic.set_title('multiple="dodge')
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[2], multiple="stack")
pic.set_title('multiple="stack"')
pic = sns.histplot(penguins, x="flipper_length_mm", hue="species", ax=ax[3], multiple="fill")
pic.set_title('multiple="fill"')
Out[16]:
Text(0.5, 1.0, 'multiple="fill"')
 
 

2.11 kde:是否生成核密度曲線

In [17]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0], kde=False)  # 默認值,不生成核密度曲線
pic.set_title('kde=False')
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], kde=True)  # 值為True,顯示核密度曲線
pic.set_title('kde=True')
Out[17]:
Text(0.5, 1.0, 'kde=True')
 
 

2.12 color:設置條形顏色

In [18]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0], color="#FFC0CB")  # 可以使16進制顏色
pic.set_title('color="#FFC0CB"')
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], color="orange")  # 也可以是 英文顏色字符串
pic.set_title('color="orange"')
Out[18]:
Text(0.5, 1.0, 'color="orange"')
 
In [19]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0], color="#FFC0CB")  # 可以使16進制顏色
pic.set_title('color="#FFC0CB"')
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], color="orange")  # 也可以是 英文顏色字符串
pic.set_title('color="orange"')
Out[19]:
Text(0.5, 1.0, 'color="orange"')
 
 

2.13 fill:條形內部是否填充顏色

In [20]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", hue='sex', ax=ax[0], fill=False)
pic.set_title('fill=False')
pic = sns.histplot(penguins, x="flipper_length_mm", hue='sex', ax=ax[1], fill=True)
pic.set_title('fill=True')
Out[20]:
Text(0.5, 1.0, 'fill=True')
 
 

2.14 legend:是否顯示圖例

In [21]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", hue="sex", ax=ax[0], legend=False)
pic.set_title('legend=False')
pic = sns.histplot(penguins, x="flipper_length_mm", hue="sex", ax=ax[1], legend=True)
pic.set_title('legend=True')
Out[21]:
Text(0.5, 1.0, 'legend=True')
 
 

2.15 shrink:縮小條形

 

shrink參數可以縮小條形增大條形之間的間隔:

In [22]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[0], shrink=0.5)
pic.set_title('shrink=0.5')
# pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], bins=10)
pic = sns.histplot(penguins, x="flipper_length_mm", ax=ax[1], shrink=0.8)
pic.set_title('shrink=0.8')
Out[22]:
Text(0.5, 1.0, 'shrink=0.8')
 
 

2.16 edgecolor:指定邊框顏色

In [47]:
_ = sns.histplot(penguins, x="flipper_length_mm", edgecolor="red")
 
 

3 barplot():條形圖

 
  • x,y:指定的x軸, y軸數據,可以是向量或者字符串,當是字符串時,一定是data中的一個key
  • hue:可以是向量(pandas中的一列,或者是list),也可以是字符串(data中的一個key),seaborn將根據這一列設置不同顏色
  • data:繪圖數據,可以是pandas.DataFrame,numpy.ndarray或者字典等
  • order:包含所有分組屬性的列表,用於指定條形順序,注意如果某個分組不在order中,該分組將不會顯示
  • hue_order:字符串組成的list,設置hue后設置各顏色順序
  • estimator:可調用對象,分組統計的方式,或者說條形圖長度所表示的意義,可以使以下值:

    • len:調用內置的len方法統計數據總長

    • np.mean:表示統計各分組平均值,這也是默認的方式

    • np.sum:表示統計各分組總和

    • np.ptp:極差

    • np.median:統計中位數

    • np.std:標准差

    • np.var:方差

  • ci:float或者"sd"或None,在估計值附近繪制置信區間的大小,如果是"sd",則跳過bootstrapping並繪制觀察的標准差,如果為None,則不執行bootstrapping,並且不繪制錯誤條。
  • orient:當x,y都是離散型或者數值型數據時,通過orient可設置圖像方向
  • color:為所有條形設置統一顏色
  • palette:顏色面板,比color參數功能更加強大,更加個性化地設置條形的顏色
  • errcolor:錯誤帶的顏色
  • errwidth:錯誤帶的寬度
  • capsize:錯誤帶“帽子”寬度
  • ax:自定義坐標系
In [23]:
tips = sns.load_dataset("tips")
In [24]:
tips.head(2)
Out[24]:
 
  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
 

3.1 x, y:傳遞數據,控制圖形方向

 

x, y為繪圖時指定的x軸和y軸數據,x、y如果有一個是離散型數據(或者說定性數據、分類數據),另一個是連續性數值數據,seaborn將會根據其中的離散型數據對另一個連續性數據進行分組統計,同時也決定繪圖的方向。如果兩個都是數值型數據,可以通過orient指定方向。

In [25]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.barplot(x="total_bill", y="day", data=tips, ax=ax[0])
pic.set_title('x="total_bill", y="day"')
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[1])
pic.set_title('x="day", y="total_bill"')
Out[25]:
Text(0.5, 1.0, 'x="day", y="total_bill"')
 
 

3.2 estimator:分組統計方式

In [26]:
fig, ax =plt.subplots(1,3,constrained_layout=True, figsize=(12, 3))
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[0], estimator=np.mean)
pic.set_title('estimator=np.mean')
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[1], estimator=np.std)
pic.set_title('np.std')
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[2], estimator=len)  # 內置方法len統計總次數
pic.set_title('len')
Out[26]:
Text(0.5, 1.0, 'len')
 
 

3.3 order:指定條形順序

In [27]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[0])
pic.set_title('default order')
pic = sns.barplot(x="day", y="total_bill", data=tips, order=['Sun', 'Sat', 'Thur', 'Fri'], ax=ax[1])
pic.set_title('"Sun", "Sat", "Thur", "Fri"')
Out[27]:
Text(0.5, 1.0, '"Sun", "Sat", "Thur", "Fri"')
 
 

3.4 hue:根據字段設置不同顏色

In [28]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[0])
pic.set_title('no hue')
pic = sns.barplot(x="day", y="total_bill", data=tips, ax=ax[1], hue="sex")
pic.set_title('hue="sex"')
Out[28]:
Text(0.5, 1.0, 'hue="sex"')
 
 

3.5 color,saturation:設置條形顏色和飽和度

 

注意,color只能一次性設置所有條形統一的顏色,如果要為條形設置不同顏色,要通過palette參數:

In [29]:
ax = sns.barplot(x="day", y="total_bill", data=tips, color="red")
 
In [30]:
ax = sns.barplot(x="day", y="total_bill", data=tips, color="red",saturation=0.5 )
 
 

3.6 errcolor:錯誤帶的顏色

In [31]:
ax = sns.barplot(x="day", y="total_bill", data=tips, errcolor="red")
 
 

3.7 errwidth:錯誤帶的寬度

In [32]:
ax = sns.barplot(x="day", y="total_bill", data=tips, errwidth=8)
 
 

3.8 capsize:錯誤帶“帽子”寬度

In [33]:
ax = sns.barplot(x="day", y="total_bill", data=tips, capsize=.2)
 
 

4 stripplot():條帶圖

 

條帶圖是是一種比較少見的圖表,綜合了散點圖和直方圖/條形圖的圖形特征和優勢,其表達的含義又與箱型圖十分類似。stripplot()參數如下:

  • x,y:指定的x軸, y軸數據,可以是向量或者字符串,當是字符串時,一定是data中的一個key
  • hue:可以是向量(pandas中的一列,或者是list),也可以是字符串(data中的一個key),seaborn將根據這一列設置不同顏色
  • data:繪圖數據,可以是pandas.DataFrame,numpy.ndarray或者字典等
  • order:包含所有分組屬性的列表,用於指定條形順序,注意如果某個分組不在order中,該分組將不會顯示
  • hue_order:字符串組成的list,設置hue后設置各顏色順序
  • jitter:抖動量,當數據很多時,增加抖動量,使散點不至於聚成一團
  • dodge:在hue基礎上,將不同顏色的散點分開
  • orient:當x,y都是離散型或者數值型數據時,通過orient可設置圖像方向
  • color:統一設置所有散點的顏色
  • palette:顏色面板
  • size:散點的大小
  • edgecolor:散點的邊框顏色
  • linewidth:散點邊框寬度
  • ax:自定義坐標系
 

4.1 x, y:傳遞數據,控制圖形方向

 

x, y為繪圖時指定的x軸和y軸數據,x、y如果有一個是離散型數據(或者說定性數據、分類數據),另一個是連續性數值數據,seaborn將會根據其中的離散型數據對另一個連續性數據進行繪制其在另一條數軸上的分布。

In [34]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[0])
pic.set_title('x="day", y="total_bill"')
pic = sns.stripplot(x="total_bill", y="day", data=tips, ax=ax[1])
pic.set_title('x="total_bill", y="day"')
Out[34]:
Text(0.5, 1.0, 'x="total_bill", y="day"')
 
 

4.2 jitter:抖動量

In [35]:
fig, ax =plt.subplots(1,3,constrained_layout=True, figsize=(12, 3))
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[0], )
pic.set_title('no jitter')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[1], jitter=0.05)
pic.set_title('jitter=0.05')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[2], jitter=0.3)
pic.set_title('jitter=0.3')
Out[35]:
Text(0.5, 1.0, 'jitter=0.3')
 
 

4.3 color:統一設置散點的顏色

In [36]:
sns.stripplot(x="day", y="total_bill", data=tips, color='red')
Out[36]:
<AxesSubplot:xlabel='day', ylabel='total_bill'>
 
 

4.4 size:散點的大小

In [37]:
fig, ax =plt.subplots(1,3,constrained_layout=True, figsize=(12, 3))
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[0], )
pic.set_title('no jitter')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[1], size=2)
pic.set_title('size=2')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[2], size=10)
pic.set_title('size=10')
Out[37]:
Text(0.5, 1.0, 'size=10')
 
 

4.5 linewidth與edgecolor:散點邊框寬度、顏色

In [38]:
fig, ax =plt.subplots(1,4,constrained_layout=True, figsize=(16, 3))
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[0], )
pic.set_title('no linewidth')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[1], linewidth=1)
pic.set_title('linewidth=1')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[2], linewidth=2)
pic.set_title('linewidth=2')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[3], linewidth=1, edgecolor="yellow")
pic.set_title('linewidth=1, edgecolor="red"')
Out[38]:
Text(0.5, 1.0, 'linewidth=1, edgecolor="red"')
 
 

4.6 hue與dodge:根據指定指定繪制散點顏色

 

hue和dodge常常需要一起配合使用,hue只是根據指定字段繪制不同顏色的散點,進一步地,dodge可以將不同顏色的散點分開

In [39]:
fig, ax =plt.subplots(1,2,constrained_layout=True, figsize=(8, 3))
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[0], hue="smoker")
pic.set_title('hue="smoker"')
pic = sns.stripplot(x="day", y="total_bill", data=tips, ax=ax[1], hue="smoker", dodge=True)
pic.set_title('hue="smoker", dodge=True')
Out[39]:
Text(0.5, 1.0, 'hue="smoker", dodge=True')
 


免責聲明!

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



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