本篇文章給大家?guī)?lái)了關(guān)于python的相關(guān)知識(shí),其中主要介紹了關(guān)于Seaborn的相關(guān)問題,包括了數(shù)據(jù)可視化處理的散點(diǎn)圖、折線圖、條形圖等等內(nèi)容,下面一起來(lái)看一下,希望對(duì)大家有幫助。
推薦學(xué)習(xí):python視頻教程
1. 安裝 seaborn
安裝:
pip install seaborn
導(dǎo)入:
import seaborn as sns
2.準(zhǔn)備數(shù)據(jù)
正式開始之前我們先用如下代碼準(zhǔn)備一組數(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ù)序號(hào)': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], '廠商編號(hào)': ['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ù)如下:
????????
3.背景與邊框
3.1 設(shè)置背景風(fēng)格
設(shè)置風(fēng)格使用的是sns.set_style()方法,且這里內(nèi)置的風(fēng)格,是用背景色表示名字的,但是實(shí)際內(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ù),則默認(rèn)表示灰色網(wǎng)格背景風(fēng)格。如果沒有set()也沒有set_style(),則為白色背景。
?
??一個(gè)可能的bug:使用relplot()方法繪制出的圖像,"ticks"樣式無(wú)效。
3.3 其他
??seaborn庫(kù)是基于matplotlib庫(kù)而封裝的,其封裝好的風(fēng)格可以更加方便我們的繪圖工作。而matplotlib庫(kù)常用的語(yǔ)句,在使用seaborn庫(kù)時(shí)也依然有效。
?
??關(guān)于設(shè)置其他風(fēng)格相關(guān)的屬性,如字體,這里有一個(gè)細(xì)節(jié)需要注意的是,這些代碼必須寫在sns.set_style()的后方才有效。如將字體設(shè)置為黑體(避免中文亂碼)的代碼:
?
plt.rcParams[‘font.sans-serif’] = [‘SimHei’]
??如果在其后方設(shè)置風(fēng)格,則設(shè)置好的字體會(huì)設(shè)置的風(fēng)格覆蓋,從而產(chǎn)生警告。其他屬性也同理。
3.2 邊框控制
sns.despine()方法
# 移除頂部和右部邊框,只保留左邊框和下邊框sns.despine()# 使兩個(gè)坐標(biāo)軸相隔一段距離(以10長(zhǎng)度為例)sns.despine(offet=10,trim=True)# 移除左邊框sns.despine(left=True)# 移除指定邊框 (以只保留底部邊框?yàn)槔﹕ns.despine(fig=None, ax=None, top=True, right=True, left=True, bottom=False, offset=None, trim=False)
4. 繪制 散點(diǎn)圖
使用seaborn庫(kù) 繪制散點(diǎn)圖,可以使用replot()方法,也可以使用scatter()方法。
replot方法的參數(shù)kind默認(rèn)是’scatter’,表示繪制散點(diǎn)圖。
hue參數(shù)表示 在該一維度上,用顏色區(qū)分
①對(duì)A屬性值和數(shù)據(jù)序號(hào)繪制散點(diǎn)圖,紅色散點(diǎn),灰色網(wǎng)格,保留左、下邊框
sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘SimHei’]
sns.relplot(x=‘?dāng)?shù)據(jù)序號(hào)’, y=‘A屬性值’, data=df1, color=‘red’)
plt.show()
??????
②對(duì)A屬性值和數(shù)據(jù)序號(hào)繪制散點(diǎn)圖,散點(diǎn)根據(jù)產(chǎn)品類型的不同顯示不同的顏色,
白色網(wǎng)格,左、下邊框:
sns.set_style(‘whitegrid’)
plt.rcParams[‘font.sans-serif’] = [‘SimHei’]
sns.relplot(x=‘?dāng)?shù)據(jù)序號(hào)’, y=‘A屬性值’, hue=‘產(chǎn)品類型’, data=df1)
plt.show()
???????
③將A屬性、B屬性、C屬性三個(gè)字段的值用不同的樣式繪制在同一張圖上(繪制散點(diǎn)圖),x軸數(shù)據(jù)是[0,2,4,6,8…]
ticks風(fēng)格(四個(gè)方向的框線都要),字體使用楷體
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()
???????
5. 繪制 折線圖
使用seaborn庫(kù)繪制折線圖, 可以使用replot()方法,也可以使用lineplot()方法。
5.1 使用 replot()方法
sns.replot()默認(rèn)繪制的是散點(diǎn)圖,繪制折線圖只需吧參數(shù)kind改為"line"。
①
需求:繪制A屬性值與數(shù)據(jù)序號(hào)的折線圖,
灰色網(wǎng)格,全局字體為楷體;并調(diào)整標(biāo)題、兩軸標(biāo)簽 的字體大小,
以及坐標(biāo)系與畫布邊緣的距離(設(shè)置該距離是因?yàn)樽煮w沒有顯示完全):
sns.set(rc={‘font.sans-serif’: “STKAITI”})
sns.relplot(x=‘?dāng)?shù)據(jù)序號(hào)’, 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()
??????????????
②
需求:繪制不同產(chǎn)品類型的A屬性折線(三條線一張圖),whitegrid風(fēng)格,字體楷體。
sns.set_style(“whitegrid”)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.relplot(x=‘?dāng)?shù)據(jù)序號(hào)’, 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()
?????????
③
??需求:將A屬性、B屬性、C屬性三個(gè)字段的值用不同的樣式繪制在同一張圖上(繪制折線圖),x軸數(shù)據(jù)是[0,2,4,6,8…]
??darkgrid風(fēng)格(四個(gè)方向的框線都要),字體使用楷體,并加入x軸標(biāo)簽,y軸標(biāo)簽和標(biāo)題。邊緣距離合適。
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()
??????????
③
??多重子圖
橫向多重子圖 col
sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.relplot(data=df1, x=“A屬性值”, y=“B屬性值”, kind=“l(fā)ine”, col=“廠商編號(hào)”)
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.1, top=0.9)
plt.show()
縱向多重子圖 row
sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.relplot(data=df1, x=“A屬性值”, y=“B屬性值”, kind=“l(fā)ine”, row=“廠商編號(hào)”)
plt.subplots_adjust(left=0.15, right=0.9, bottom=0.1, top=0.95)
plt.show()
?????????????
5.2 使用 lineplot()方法
使用lineplot()方法繪制折線圖,其他細(xì)節(jié)基本同上,示例代碼如下:
sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.lineplot(x=‘?dāng)?shù)據(jù)序號(hào)’, 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()
????????
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()
????????
6. 繪制直方圖 displot()
繪制直方圖使用的是sns.displot()方法
bins=6 表示 分成六個(gè)區(qū)間繪圖
rug=True 表示在x軸上顯示觀測(cè)的小細(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()
????????
隨機(jī)生成300個(gè)正態(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()
?????????????
7. 繪制條形圖 barplot()
繪制條形圖使用的是barplot()方法
?
以產(chǎn)品類型 字段數(shù)據(jù)作為x軸數(shù)據(jù),A屬性值數(shù)據(jù)作為y軸數(shù)據(jù)。按照廠商編號(hào)字段的不同進(jìn)行分類。
具體如下:
sns.set_style(‘darkgrid’)
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.barplot(x=“產(chǎn)品類型”, y=‘A屬性值’, hue=“廠商編號(hào)”, 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()
?????????
8. 繪制線性回歸模型
繪制線性回歸模型使用的是lmplot()方法。
主要的參數(shù)為x, y, data。分別表示x軸數(shù)據(jù)、y軸數(shù)據(jù)和數(shù)據(jù)集數(shù)據(jù)。
?
除此之外,同上述所講,還可以通過(guò)hue指定分類的變量;
通過(guò)col指定列分類變量,以繪制 橫向多重子圖;
通過(guò)row指定行分類變量,以繪制 縱向多重子圖;
通過(guò)col_wrap控制每行子圖的數(shù)量;
通過(guò)size可以控制子圖的高度;
通過(guò)markers可以控制點(diǎn)的形狀。
?
下邊對(duì) 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()
???????????
9. 繪制 核密度圖 kdeplot()
9.1 一般核密度圖
繪制和密度圖,可以讓我們更直觀地看出樣本數(shù)據(jù)的分布特征。繪制核密度圖使用的方法是kdeplot()方法。
?
對(duì)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()
?????????
9.2 邊際核密度圖
繪制邊際核密度圖時(shí)使用的是sns.jointplot()方法。參數(shù)kind應(yīng)為"kde"。使用該方法時(shí),默認(rèn)使用的是dark樣式。且不建議手動(dòng)添加其他樣式,否則可能使圖像無(wú)法正常顯示。
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.jointplot(x=df1[“A屬性值”], y=df1[“B屬性值”], kind=“kde”, space=0)
plt.show()
????????
10. 繪制 箱線圖 boxplot()
繪制箱線圖使用到的是boxplot()方法。
基本的參數(shù)有x, y, data。
?
除此之外 還可以有
hue 表示分類字段
width 可以調(diào)節(jié)箱體的寬度
notch 表示中間箱體是否顯示缺口,默認(rèn)False不顯示。
鑒于前邊的數(shù)據(jù)數(shù)據(jù)量不太夠不便展示,這里再生成一組數(shù)據(jù):
np.random.seed(13)
Y = np.random.randint(20, 150, 360)
df2 = pd.DataFrame(
{‘廠商編號(hào)’: [‘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()
????????
交換x、y軸數(shù)據(jù)后:
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.boxplot(y=‘產(chǎn)品類型’, x=‘XXX屬性值’, data=df2)
plt.show()
可以看到箱線圖的方向也隨之改變
????????
將廠商編號(hào)作為分類字段:
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.boxplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2, hue=“廠商編號(hào)”)
plt.show()
????????
11. 繪制 提琴圖 violinplot()
提琴圖結(jié)合了箱線圖和核密度圖的特征,用于展示數(shù)據(jù)的分布形狀。
使用violinplot()方法繪制提琴圖。
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.violinplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2)
plt.show()
????????
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.violinplot(x=‘XXX屬性值’, y=‘產(chǎn)品類型’, data=df2)
plt.show()
????????
plt.rcParams[‘font.sans-serif’] = [‘STKAITI’]
sns.violinplot(x=‘產(chǎn)品類型’, y=‘XXX屬性值’, data=df2, hue=“廠商編號(hào)”)
plt.show()
????????
12. 繪制 熱力圖 heatmap()
以雙色球中獎(jiǎng)號(hào)碼數(shù)據(jù)為例繪制熱力圖,這里數(shù)據(jù)采用隨機(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(‘中獎(jiǎng)號(hào)碼位數(shù)’)
plt.ylabel(‘雙色球數(shù)字’)
x = [‘第1位’, ‘第2位’, ‘第3位’, ‘第4位’, ‘第5位’, ‘第6位’, ‘第7位’]
plt.xticks(range(0, 7, 1), x, ha=‘left’)
plt.show()
????????
推薦學(xué)習(xí):python視頻教程