Python之Seaborn實例分析

今天小編給大家分享一下Python之Seaborn實例分析的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

武夷山ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!

Python之Seaborn實例分析

1. 安裝 seaborn

安裝:

pip install seaborn

導(dǎo)入:

import seaborn as sns


2.準備數(shù)據(jù)

正式開始之前我們先用如下代碼準備一組數(shù)據(jù),方便展示使用。

import pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as snspd.set_option('display.unicode.east_asian_width', True)df1 = pd.DataFrame(    {'數(shù)據(jù)序號': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],     '廠商編號': ['001', '001', '001', '002', '002', '002', '003', '003', '003', '004', '004', '004'],     '產(chǎn)品類型': ['AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC', 'AAA', 'BBB', 'CCC'],     'A屬性值': [40, 70, 60, 75, 90, 82, 73, 99, 125, 105, 137, 120],     'B屬性值': [24, 36, 52, 32, 49, 68, 77, 90, 74, 88, 98, 99],     'C屬性值': [30, 36, 55, 46, 68, 77, 72, 89, 99, 90, 115, 101]    })print(df1)

生成一組數(shù)據(jù)如下:

????????Python之Seaborn實例分析


3.背景與邊框


3.1 設(shè)置背景風(fēng)格

設(shè)置風(fēng)格使用的是sns.set_style()方法,且這里內(nèi)置的風(fēng)格,是用背景色表示名字的,但是實際內(nèi)容不限于背景色。

sns.set_style()

?
可以選擇的背景風(fēng)格有:

  • whitegrid ?白色網(wǎng)格

  • dark ?灰色背景

  • white ?白色背景

  • ticks ?四周帶刻度線的白色背景

?
sns.set()
?
sns.set_style(“darkgrid”)
?
sns.set_style(“whitegrid”)
?
sns.set_style(“dark”)
?
sns.set_style(“white”)
?
sns.set_style(“ticks”)
?

??其中sns.set()表示使用自定義樣式,如果沒有傳入?yún)?shù),則默認表示灰色網(wǎng)格背景風(fēng)格。如果沒有set()也沒有set_style(),則為白色背景。
?
??一個可能的bug:使用relplot()方法繪制出的圖像,"ticks"樣式無效。


3.3 其他

??seaborn庫是基于matplotlib庫而封裝的,其封裝好的風(fēng)格可以更加方便我們的繪圖工作。而matplotlib庫常用的語句,在使用seaborn庫時也依然有效。
?
?關(guān)于設(shè)置其他風(fēng)格相關(guān)的屬性,如字體,這里有一個細節(jié)需要注意的是,這些代碼必須寫在sns.set_style()的后方才有效。如將字體設(shè)置為黑體(避免中文亂碼)的代碼:
?

plt.rcParams[‘font.sans-serif’] = [‘SimHei’]

??如果在其后方設(shè)置風(fēng)格,則設(shè)置好的字體會設(shè)置的風(fēng)格覆蓋,從而產(chǎn)生警告。其他屬性也同理。


3.2 邊框控制

sns.despine()方法

# 移除頂部和右部邊框,只保留左邊框和下邊框sns.despine()# 使兩個坐標軸相隔一段距離(以10長度為例)sns.despine(offet=10,trim=True)# 移除左邊框sns.despine(left=True)# 移除指定邊框 (以只保留底部邊框為例)sns.despine(fig=None, ax=None, top=True, right=True, left=True, bottom=False, offset=None, trim=False)

4. 繪制 散點圖

使用seaborn庫 繪制散點圖,可以使用replot()方法,也可以使用scatter()方法。

replot方法的參數(shù)kind默認是’scatter’,表示繪制散點圖。
hue參數(shù)表示 在該一維度上,用顏色區(qū)分

①對A屬性值和數(shù)據(jù)序號繪制散點圖,紅色散點,灰色網(wǎng)格,保留左、下邊框

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘SimHei’]
sns.relplot(x=‘?dāng)?shù)據(jù)序號’, y=‘A屬性值’, data=df1, color=‘red’)
plt.show()

??????Python之Seaborn實例分析


②對A屬性值和數(shù)據(jù)序號繪制散點圖,散點根據(jù)產(chǎn)品類型的不同顯示不同的顏色,
白色網(wǎng)格,左、下邊框:

sns.set_style(‘whitegrid’)
plt.rcParams[‘font.sans-serif’] = [‘SimHei’]
sns.relplot(x=‘?dāng)?shù)據(jù)序號’, y=‘A屬性值’, hue=‘產(chǎn)品類型’, data=df1)
plt.show()

???????Python之Seaborn實例分析


③將A屬性、B屬性、C屬性三個字段的值用不同的樣式繪制在同一張圖上(繪制散點圖),x軸數(shù)據(jù)是[0,2,4,6,8…]
ticks風(fēng)格(四個方向的框線都要),字體使用楷體

sns.set_style(‘ticks’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
df2 = df1.copy()
df2.index = list(range(0, len(df2)*2, 2))
dfs = [df2[‘A屬性值’], df2[‘B屬性值’], df2[‘C屬性值’]]
sns.scatterplot(data=dfs)
plt.show()

???????Python之Seaborn實例分析


5. 繪制 折線圖

使用seaborn庫繪制折線圖, 可以使用replot()方法,也可以使用lineplot()方法。

5.1 使用 replot()方法

sns.replot()默認繪制的是散點圖,繪制折線圖只需吧參數(shù)kind改為"line"。

需求:繪制A屬性值與數(shù)據(jù)序號的折線圖,
灰色網(wǎng)格,全局字體為楷體;并調(diào)整標題、兩軸標簽 的字體大小,
以及坐標系與畫布邊緣的距離(設(shè)置該距離是因為字體沒有顯示完全):

sns.set(rc={‘font.sans-serif’: “STKAITI”})
sns.relplot(x=‘?dāng)?shù)據(jù)序號’, y=‘A屬性值’, data=df1, color=‘purple’, kind=‘line’)
plt.title(“繪制折線圖”, fontsize=18)
plt.xlabel(‘num’, fontsize=18)
plt.ylabel(‘A屬性值’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

??????????????Python之Seaborn實例分析



需求:繪制不同產(chǎn)品類型的A屬性折線(三條線一張圖),whitegrid風(fēng)格,字體楷體。

sns.set_style(“whitegrid”)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.relplot(x=‘?dāng)?shù)據(jù)序號’, y=‘A屬性值’, hue=‘產(chǎn)品類型’, data=df1, kind=‘line’)
plt.title(“繪制折線圖”, fontsize=18)
plt.xlabel(‘num’, fontsize=18)
plt.ylabel(‘A屬性值’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

?????????Python之Seaborn實例分析



?需求:將A屬性、B屬性、C屬性三個字段的值用不同的樣式繪制在同一張圖上(繪制折線圖),x軸數(shù)據(jù)是[0,2,4,6,8…]
??darkgrid風(fēng)格(四個方向的框線都要),字體使用楷體,并加入x軸標簽,y軸標簽和標題。邊緣距離合適。

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
df2 = df1.copy()
df2.index = list(range(0, len(df2)*2, 2))
dfs = [df2[‘A屬性值’], df2[‘B屬性值’], df2[‘C屬性值’]]
sns.relplot(data=dfs, kind=“l(fā)ine”)
plt.title(“繪制折線圖”, fontsize=18)
plt.xlabel(‘num’, fontsize=18)
plt.ylabel(‘A屬性值’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

??????????Python之Seaborn實例分析



?多重子圖

橫向多重子圖 col

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.relplot(data=df1, x=“A屬性值”, y=“B屬性值”, kind=“l(fā)ine”, col=“廠商編號”)
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.1, top=0.9)
plt.show()

Python之Seaborn實例分析

縱向多重子圖 row

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.relplot(data=df1, x=“A屬性值”, y=“B屬性值”, kind=“l(fā)ine”, row=“廠商編號”)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.95)
plt.show()

?????????????Python之Seaborn實例分析


5.2 使用 lineplot()方法

使用lineplot()方法繪制折線圖,其他細節(jié)基本同上,示例代碼如下:

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.lineplot(x=‘?dāng)?shù)據(jù)序號’, y=‘A屬性值’, data=df1, color=‘purple’)
plt.title(“繪制折線圖”, fontsize=18)
plt.xlabel(‘num’, fontsize=18)
plt.ylabel(‘A屬性值’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

????????Python之Seaborn實例分析


sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
df2 = df1.copy()
df2.index = list(range(0, len(df2)*2, 2))
dfs = [df2[‘A屬性值’], df2[‘B屬性值’], df2[‘C屬性值’]]
sns.lineplot(data=dfs)
plt.title(“繪制折線圖”, fontsize=18)
plt.xlabel(‘num’, fontsize=18)
plt.ylabel(‘A屬性值’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

????????Python之Seaborn實例分析


6. 繪制直方圖 displot()

繪制直方圖使用的是sns.displot()方法

bins=6 表示 分成六個區(qū)間繪圖
rug=True 表示在x軸上顯示觀測的小細條
kde=True表示顯示核密度曲線

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.displot(data=df1[[‘C屬性值’]], bins=6, rug=True, kde=True)
plt.title(“直方圖”, fontsize=18)
plt.xlabel(‘C屬性值’, fontsize=18)
plt.ylabel(‘?dāng)?shù)量’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

????????Python之Seaborn實例分析


隨機生成300個正態(tài)分布數(shù)據(jù),并繪制直方圖,顯示核密度曲線

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
np.random.seed(13)
Y = np.random.randn(300)
sns.displot(Y, bins=9, rug=True, kde=True)
plt.title(“直方圖”, fontsize=18)
plt.xlabel(‘C屬性值’, fontsize=18)
plt.ylabel(‘?dāng)?shù)量’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.9)
plt.show()

?????????????Python之Seaborn實例分析


7. 繪制條形圖 barplot()

繪制條形圖使用的是barplot()方法
?
以產(chǎn)品類型 字段數(shù)據(jù)作為x軸數(shù)據(jù),A屬性值數(shù)據(jù)作為y軸數(shù)據(jù)。按照廠商編號字段的不同進行分類。
具體如下:

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.barplot(x=“產(chǎn)品類型”, y=‘A屬性值’, hue=“廠商編號”, data=df1)
plt.title(“條形圖”, fontsize=18)
plt.xlabel(‘產(chǎn)品類型’, fontsize=18)
plt.ylabel(‘?dāng)?shù)量’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.15, top=0.9)
plt.show()

?????????Python之Seaborn實例分析


8. 繪制線性回歸模型

繪制線性回歸模型使用的是lmplot()方法。
主要的參數(shù)為x, y, data。分別表示x軸數(shù)據(jù)、y軸數(shù)據(jù)和數(shù)據(jù)集數(shù)據(jù)。
?
除此之外,同上述所講,還可以通過hue指定分類的變量;
通過col指定列分類變量,以繪制 橫向多重子圖;
通過row指定行分類變量,以繪制 縱向多重子圖;
通過col_wrap控制每行子圖的數(shù)量;
通過size可以控制子圖的高度;
通過markers可以控制點的形狀。
?
下邊對 X屬性值 和 Y屬性值 做線性回歸,代碼如下:

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.lmplot(x=“A屬性值”, y=‘B屬性值’, data=df1)
plt.title(“線性回歸模型”, fontsize=18)
plt.xlabel(‘A屬性值’, fontsize=18)
plt.ylabel(‘B屬性值’, fontsize=16)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.15, top=0.9)
plt.show()

???????????Python之Seaborn實例分析


9. 繪制 核密度圖 kdeplot()

9.1 一般核密度圖

繪制和密度圖,可以讓我們更直觀地看出樣本數(shù)據(jù)的分布特征。繪制核密度圖使用的方法是kdeplot()方法。
?
對A屬性值和B屬性值繪制核密度圖,
將shade設(shè)置為True可以顯示包圍的陰影,否則只有線條。

sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.kdeplot(df1[“A屬性值”], shade=True, data=df1, color=‘r’)
sns.kdeplot(df1[“B屬性值”], shade=True, data=df1, color=‘g’)
plt.title(“核密度圖”, fontsize=18)
plt.xlabel(‘Value’, fontsize=18)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.15, top=0.9)
plt.show()

?????????Python之Seaborn實例分析


9.2 邊際核密度圖

繪制邊際核密度圖時使用的是sns.jointplot()方法。參數(shù)kind應(yīng)為"kde"。使用該方法時,默認使用的是dark樣式。且不建議手動添加其他樣式,否則可能使圖像無法正常顯示。

plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.jointplot(x=df1[“A屬性值”], y=df1[“B屬性值”], kind=“kde”, space=0)
plt.show()

????????Python之Seaborn實例分析


10. 繪制 箱線圖 boxplot()

繪制箱線圖使用到的是boxplot()方法。
基本的參數(shù)有x, y, data。
?
除此之外 還可以有
hue 表示分類字段
width 可以調(diào)節(jié)箱體的寬度
notch 表示中間箱體是否顯示缺口,默認False不顯示。

鑒于前邊的數(shù)據(jù)數(shù)據(jù)量不太夠不便展示,這里再生成一組數(shù)據(jù):

np.random.seed(13)
Y = np.random.randint(20, 150, 360)
df2 = pd.DataFrame(
{‘廠商編號’: [‘001’, ‘001’, ‘001’, ‘002’, ‘002’, ‘002’, ‘003’, ‘003’, ‘003’, ‘004’, ‘004’, ‘004’] * 30,
‘產(chǎn)品類型’: [‘AAA’, ‘BBB’, ‘CCC’, ‘AAA’, ‘BBB’, ‘CCC’, ‘AAA’, ‘BBB’, ‘CCC’, ‘AAA’, ‘BBB’, ‘CCC’] * 30,
‘XXX屬性值’: Y
}
)


生成好后,開始繪制箱線圖:

plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.boxplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2)
plt.show()

????????Python之Seaborn實例分析


交換x、y軸數(shù)據(jù)后:

plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.boxplot(y=‘產(chǎn)品類型’, x=‘XXX屬性值’, data=df2)
plt.show()

可以看到箱線圖的方向也隨之改變

????????Python之Seaborn實例分析


將廠商編號作為分類字段:

plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.boxplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2, hue=“廠商編號”)
plt.show()

????????Python之Seaborn實例分析


11. 繪制 提琴圖 violinplot()

提琴圖結(jié)合了箱線圖和核密度圖的特征,用于展示數(shù)據(jù)的分布形狀。
使用violinplot()方法繪制提琴圖。

plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.violinplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2)
plt.show()

????????Python之Seaborn實例分析


plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.violinplot(x=‘XXX屬性值’, y=‘產(chǎn)品類型’, data=df2)
plt.show()

????????Python之Seaborn實例分析


plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.violinplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2, hue=“廠商編號”)
plt.show()

????????Python之Seaborn實例分析


12. 繪制 熱力圖 heatmap()

以雙色球中獎號碼數(shù)據(jù)為例繪制熱力圖,這里數(shù)據(jù)采用隨機數(shù)生成。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
?
sns.set()
plt.figure(figsize=(6,6))
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
?
s1 = np.random.randint(0, 200, 33)
s2 = np.random.randint(0, 200, 33)
s3 = np.random.randint(0, 200, 33)
s4 = np.random.randint(0, 200, 33)
s5 = np.random.randint(0, 200, 33)
s6 = np.random.randint(0, 200, 33)
s7 = np.random.randint(0, 200, 33)
data = pd.DataFrame(
{‘一’: s1,
‘二’: s2,
‘三’: s3,
‘四’:s4,
‘五’:s5,
‘六’:s6,
‘七’:s7
}
)
?
plt.title(‘雙色球熱力圖’)
sns.heatmap(data, annot=True, fmt=‘d’, lw=0.5)
plt.xlabel(‘中獎號碼位數(shù)’)
plt.ylabel(‘雙色球數(shù)字’)
x = [‘第1位’, ‘第2位’, ‘第3位’, ‘第4位’, ‘第5位’, ‘第6位’, ‘第7位’]
plt.xticks(range(0, 7, 1), x, ha=‘left’)
plt.show()

????????Python之Seaborn實例分析

以上就是“Python之Seaborn實例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

分享題目:Python之Seaborn實例分析
文章來源:http://www.muchs.cn/article8/jpcoop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、關(guān)鍵詞優(yōu)化商城網(wǎng)站、ChatGPT、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化