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: 繪圖的坐標軸實例
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
penguins = sns.load_dataset('penguins',data_home='.')
penguins.head(2)
2.1 為圖像設置標題¶
histplot()方法返回值為matplotlib.axes._subplots.AxesSubplot類實例,通過實例的set_title()方法可以為圖像添加標題:
pic = sns.histplot(penguins, x="flipper_length_mm")
pic.set_title('flipper_length_mm')
2.2 ax:自定義繪圖坐標系¶
在不傳遞ax參數時,seaborn會自行創建坐標系進行繪圖,我們也可以自己創建坐標系,通過ax參數傳遞,這樣做的好處是可以靈活繪制多個子圖:
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):三大容器對象與常用設置
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軸為統計次數:
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')
2.4 stat:y軸顯示數據的方式¶
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:指定分箱方式¶
指定分箱個數或者每個條形區間進行繪圖:
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]')
也可以指定分箱的規則:
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')
2.6 binwidth:設置柱形寬度¶
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:累積每個條形高度進行繪圖¶
sns.histplot(penguins, x="flipper_length_mm", cumulative=True)
sns.histplot(penguins, x="flipper_length_mm", multiple="layer")
2.8 hue:顏色區分條形組成¶
_ = sns.histplot(penguins, x="flipper_length_mm", hue="species")
2.9 element¶
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"')
2.10 multiple¶
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"')
2.11 kde:是否生成核密度曲線¶
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')
2.12 color:設置條形顏色¶
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"')
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"')
2.13 fill:條形內部是否填充顏色¶
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')
2.14 legend:是否顯示圖例¶
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')
2.15 shrink:縮小條形¶
shrink參數可以縮小條形增大條形之間的間隔:
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')
2.16 edgecolor:指定邊框顏色¶
_ = 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:自定義坐標系
tips = sns.load_dataset("tips")
tips.head(2)
3.1 x, y:傳遞數據,控制圖形方向¶
x, y為繪圖時指定的x軸和y軸數據,x、y如果有一個是離散型數據(或者說定性數據、分類數據),另一個是連續性數值數據,seaborn將會根據其中的離散型數據對另一個連續性數據進行分組統計,同時也決定繪圖的方向。如果兩個都是數值型數據,可以通過orient指定方向。
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"')
3.2 estimator:分組統計方式¶
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')
3.3 order:指定條形順序¶
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"')
3.4 hue:根據字段設置不同顏色¶
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"')
3.5 color,saturation:設置條形顏色和飽和度¶
注意,color只能一次性設置所有條形統一的顏色,如果要為條形設置不同顏色,要通過palette參數:
ax = sns.barplot(x="day", y="total_bill", data=tips, color="red")
ax = sns.barplot(x="day", y="total_bill", data=tips, color="red",saturation=0.5 )
3.6 errcolor:錯誤帶的顏色¶
ax = sns.barplot(x="day", y="total_bill", data=tips, errcolor="red")
3.7 errwidth:錯誤帶的寬度¶
ax = sns.barplot(x="day", y="total_bill", data=tips, errwidth=8)
3.8 capsize:錯誤帶“帽子”寬度¶
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將會根據其中的離散型數據對另一個連續性數據進行繪制其在另一條數軸上的分布。
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"')
4.2 jitter:抖動量¶
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')
4.3 color:統一設置散點的顏色¶
sns.stripplot(x="day", y="total_bill", data=tips, color='red')
4.4 size:散點的大小¶
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')
4.5 linewidth與edgecolor:散點邊框寬度、顏色¶
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"')
4.6 hue與dodge:根據指定指定繪制散點顏色¶
hue和dodge常常需要一起配合使用,hue只是根據指定字段繪制不同顏色的散點,進一步地,dodge可以將不同顏色的散點分開
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')
