Seaborn是一個(gè)統(tǒng)計(jì)數(shù)據(jù)可視化的Python庫(kù),官方網(wǎng)站在這里:
https://seaborn.pydata.org
它是基于Matplotlib庫(kù)的可視化工具,提供了一些高級(jí)繪圖API。也就是說(shuō),Seaborn庫(kù)繪圖相比matplotlib而言沒(méi)有那么繁瑣了,簡(jiǎn)潔的代碼可以繪制一幅很好的圖形。
Seaborn的繪圖數(shù)據(jù)對(duì)象是DataFrame對(duì)象或者是array數(shù)組。一般我們使用DataFrame作為它的繪圖對(duì)象。在正式地繪圖之前,我們先來(lái)看下這個(gè)庫(kù)的繪圖風(fēng)格和顏色模式吧。
先看繪圖風(fēng)格,我們之前說(shuō)過(guò)matplotlib的繪圖風(fēng)格有很多種,其中一個(gè)就是seaborn風(fēng)格。它正式Seaborn庫(kù)中的繪圖風(fēng)格。那我們來(lái)看下具體的風(fēng)格吧,以iris數(shù)據(jù)集的箱線圖為例。
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris') # seaborn自帶的iris數(shù)據(jù)集
fig, ax = plt.subplots(figsize=(6,6))
ax.boxplot(df.iloc[:50,:2])
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
這是普通的matplotlib繪圖的風(fēng)格,那么我們要是seaborn的繪圖默認(rèn)風(fēng)格,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris') # seaborn自帶的iris數(shù)據(jù)集
sns.set_theme() # 設(shè)置默認(rèn)的Seaborn繪圖風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
ax.boxplot(df.iloc[:50,:2])
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
實(shí)際上,這個(gè)函數(shù)有一些選項(xiàng)可以調(diào)整的,第一個(gè)參數(shù)context,它的參數(shù)可以是字典或者是幾個(gè)既定好的字符串,分別代表幾個(gè)不同的風(fēng)格,詳細(xì)的參數(shù)取值可以參考這里
https://seaborn.pydata.org/generated/seaborn.plotting\_context.html
下面就不同的參數(shù)給出不同風(fēng)格的圖形,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris') # seaborn自帶的iris數(shù)據(jù)集
sns.set_theme(context='notebook') # 默認(rèn)風(fēng)格
fig1 = plt.figure(1,figsize=(6,6))
ax1 = fig1.add_subplot()
ax1.boxplot(df.iloc[:50,:2])
sns.set_theme(context='paper')
fig2 = plt.figure(2,figsize=(6,6))
ax2 = fig2.add_subplot()
ax2.boxplot(df.iloc[:50,:2])
sns.set_theme(context='talk')
fig3 = plt.figure(3,figsize=(6,6))
ax3 = fig3.add_subplot()
ax3.boxplot(df.iloc[:50,:2])
sns.set_theme(context='poster')
fig4 = plt.figure(4,figsize=(6,6))
ax4 = fig4.add_subplot()
ax4.boxplot(df.iloc[:50,:2])
plt.show()
程序輸出的結(jié)果分別見(jiàn)下圖。
其實(shí)繪圖風(fēng)格不僅僅是有context這個(gè)參數(shù)決定的,還有一個(gè)比較重要的參數(shù)style,它是用來(lái)控制軸線樣式的。它不同的取值有darkgrid(默認(rèn)值),whitegrid,dark,white,ticks,不同的取值搭配context='notebook'的繪圖風(fēng)格,執(zhí)行下面的代碼即可得知。
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('iris') # seaborn自帶的iris數(shù)據(jù)集
sns.set_theme(style='ticks') # 默認(rèn)風(fēng)格
fig1 = plt.figure(1,figsize=(6,6))
ax1 = fig1.add_subplot()
ax1.boxplot(df.iloc[:50,:2])
sns.set_theme(style='whitegrid')
fig2 = plt.figure(2,figsize=(6,6))
ax2 = fig2.add_subplot()
ax2.boxplot(df.iloc[:50,:2])
sns.set_theme(style='dark')
fig3 = plt.figure(3,figsize=(6,6))
ax3 = fig3.add_subplot()
ax3.boxplot(df.iloc[:50,:2])
sns.set_theme(style='white')
fig4 = plt.figure(4,figsize=(6,6))
ax4 = fig4.add_subplot()
ax4.boxplot(df.iloc[:50,:2])
plt.show()
程序輸出的結(jié)果分別見(jiàn)下圖。
你會(huì)發(fā)現(xiàn),似乎指定style參數(shù)之后,context參數(shù)好像失效了?其實(shí)這個(gè)并不是很重要,我認(rèn)為Seaborn默認(rèn)的繪圖風(fēng)格是好看的,至少比matplotlib默認(rèn)的繪圖風(fēng)格要好看。
所謂的繪圖顏色模式,就是指定用哪個(gè)顏色來(lái)繪圖,通過(guò)set_theme()函數(shù)的參數(shù)palette指定,它的具體取值有字符串:deep,muted,bright,pastel,dark,colorblind,或者是matplotlib的colormap的名稱。如果你不記得了colormap有哪些,那么可以參考這里
https://matplotlib.org/stable/tutorials/colors/colormaps.html
還有一些其他取值,可以參考這里
https://seaborn.pydata.org/generated/seaborn.color_palette.html
如果我們想要看一下具體顏色,可以通過(guò)下面的代碼呈現(xiàn):
import seaborn as sns
import matplotlib.pyplot as plt
sns.color_palette('deep')
sns.color_palette('muted')
sns.color_palette('bright')
sns.color_palette('pastel')
sns.color_palette('dark')
sns.color_palette('colorblind')
在notebook環(huán)境下逐行運(yùn)行,部分結(jié)果見(jiàn)下圖。
散點(diǎn)圖是用來(lái)描述變量之間關(guān)系的統(tǒng)計(jì)圖形。繪制散點(diǎn)圖,在Seaborn中有兩種方式,現(xiàn)在其實(shí)是三種方式。其一是使用Figure-level function,其二是使用Axes-level function,還有一個(gè)是新版本庫(kù)新增的object方法。
按照我學(xué)習(xí)matplotlib的繪圖習(xí)慣,這里的第二種方式Axes-level function我是比較容易理解的。它返回的是一個(gè)Axes對(duì)象,也可以傳遞一個(gè)Axes圖形對(duì)象作為當(dāng)前繪制的圖形。
下面就繪制一幅散點(diǎn)圖,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
iris = sns.load_dataset('iris')
sns.scatterplot(data=iris,x=iris.iloc[:50,0],y=iris.iloc[:50,1], ax=ax)
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
這個(gè)函數(shù)返回的是仍然是ax對(duì)象。它可以很方便地繪制分組散點(diǎn)圖,通過(guò)參數(shù)hue指定即可,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
iris = sns.load_dataset('iris')
sns.scatterplot(data=iris,x='sepal_length',y='sepal_width', ax=ax, hue='species')
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
如果你想要對(duì)不同的分類變量下散點(diǎn)樣式進(jìn)行更改,可以通過(guò)參數(shù)style很方便地指定一個(gè)分類變量,作為不同的marker散點(diǎn)樣式,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
tips = sns.load_dataset('tips')
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='time', style='time')
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
這里的marker樣式是隨機(jī)指定的。還可以通過(guò)size來(lái)指定散點(diǎn)的大小,這就是繪制氣泡圖了,通過(guò)patelle來(lái)指定繪圖顏色模式,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
tips = sns.load_dataset('tips')
sns.scatterplot(data=tips, x='total_bill', y='tip', hue='smoker',
size='size', palette='GnBu')
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
這是繪制散點(diǎn)圖的方式之一,具體的參數(shù)請(qǐng)參見(jiàn)這里
https://seaborn.pydata.org/generated/seaborn.scatterplot.html
另外一個(gè)繪制散點(diǎn)圖的方式就是使用Figure-level function,主要是函數(shù)relplot()實(shí)現(xiàn)。下面仍然是繪制散點(diǎn)圖,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
tips = sns.load_dataset('tips')
fig = sns.relplot(kind='scatter', data=tips, x='total_bill', y='tip', hue='smoker',
palette='Oranges', height=6, aspect=1)
# height指定圖形的高度(英寸),寬度為height*aspect
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
其他的參數(shù)指定和scatterplot函數(shù)是類似的,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
tips = sns.load_dataset('tips')
fig = sns.relplot(kind='scatter', data=tips, x='total_bill', y='tip', hue='smoker',
style='time', palette='YlGn', height=6,aspect=1)
# height指定圖形的高度(英寸),寬度為height*aspect
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
再來(lái)看指定散點(diǎn)大小的氣泡圖,還是通過(guò)參數(shù)size,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
tips = sns.load_dataset('tips')
fig = sns.relplot(kind='scatter',data=tips, x='total_bill', y='tip', size='size',
hue='sex', palette='PRGn', height=6, aspect=1)
# height指定圖形的高度(英寸),寬度為height*aspect
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
有關(guān)relplot函數(shù)的更多詳細(xì)參數(shù)請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.relplot.html
前面介紹了兩種繪制散點(diǎn)圖的方法,是經(jīng)典的繪制散點(diǎn)圖API,還有一個(gè)Object方法,下面來(lái)看下,執(zhí)行下面的代碼:
import seaborn as sns
import seaborn.objects as so
sns.set_theme() # 設(shè)置seaborn繪圖風(fēng)格
penguins = sns.load_dataset('penguins')
(
so.Plot(data=penguins, x='bill_length_mm', y='bill_depth_mm')
.add(so.Dot()).layout(size=(6,6)).show()
)
# 設(shè)置圖形是6英寸乘以6英寸的大小,so.Dot()表示繪制散點(diǎn)圖
程序輸出的結(jié)果見(jiàn)下圖。
如果我們想要改變散點(diǎn)的顏色,可以執(zhí)行下面的代碼:
import seaborn as sns
import seaborn.objects as so
sns.set_theme() # 設(shè)置seaborn繪圖風(fēng)格
penguins = sns.load_dataset('penguins')
(
so.Plot
(
data=penguins, x='bill_length_mm', y='bill_depth_mm',
edgecolor='sex', edgewidth='body_mass_g'
)
.add(so.Dot(color='xkcd:plum',alpha=0.2))
.layout(size=(6,6))
.show()
)
# 通過(guò)參數(shù)color和alpha來(lái)指定顏色
程序輸出的結(jié)果見(jiàn)下圖。
有關(guān)函數(shù)so.Plot()的更多參數(shù)請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.objects.Plot.html
有關(guān)散點(diǎn)函數(shù)so.Dot()的更多參數(shù)請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.objects.Dot.html
但是這種繪制散點(diǎn)圖的方式有一個(gè)缺點(diǎn)就是無(wú)法繪制分組散點(diǎn)圖?這一點(diǎn)好像是的。而且它有一些詳細(xì)的參數(shù)API,很類似于matplotlib繪制散點(diǎn)圖的參數(shù)??梢哉f(shuō),它的封裝性沒(méi)有那么強(qiáng),靈活性更強(qiáng),便于修改。
線圖是一般是用來(lái)展示趨勢(shì)性數(shù)據(jù)的,也可以用來(lái)展示兩個(gè)變量之間的關(guān)系。
先看第一種繪制線圖的方式,使用Axes-level function,lineplot()函數(shù),展示時(shí)間序列數(shù)據(jù)最適合使用線圖,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置Seaborn繪圖風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
dowjones = sns.load_dataset('dowjones')
sns.lineplot(data=dowjones, x='Date', y='Price',ax=ax)
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
還可以通過(guò)hue參數(shù)指定分組變量,繪制線圖。執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置Seaborn繪圖風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
flights = sns.load_dataset('flights')
sns.lineplot(data=flights, x='year', y='passengers',ax=ax,hue='month',palette='Spectral')
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
有意思的是這個(gè)數(shù)據(jù)結(jié)果是一般的列變量形式,但是時(shí)間序列數(shù)據(jù)也可能是每一列都是一個(gè)單獨(dú)的月份數(shù)據(jù),執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置Seaborn繪圖風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
flights = sns.load_dataset('flights')
flights_wide = flights.pivot(index='year', columns='month', values='passengers')
sns.lineplot(data=flights_wide, ax=ax ,palette='BuGn')
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
這種數(shù)據(jù)結(jié)果是以列作為每一個(gè)月份,行作為年份,中間的值就是上面數(shù)據(jù)中的passengers變量值,繪制線圖也是以列作為一個(gè)變量繪制的,不需要指定參數(shù)hue了,直接給定一個(gè)數(shù)據(jù)即可。
單個(gè)線圖是默認(rèn)繪制置信區(qū)間的,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置Seaborn繪圖風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
flights = sns.load_dataset('flights')
sns.lineplot(data=flights, x='year', y='passengers', ax=ax,
color='xkcd:plum', alpha=0.3)
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
這里的置信區(qū)間是百分之95的置信區(qū)間,以置信帶的形式呈現(xiàn),通過(guò)參數(shù)errerbar指定,errstyle參數(shù)指定的是誤差的呈現(xiàn)形式,有bars和band兩種形式。有關(guān)具體的errerbar內(nèi)容下面會(huì)介紹到。
如果我們并不希望繪制這個(gè)誤差范圍呢?使用參數(shù)estimator=None即可,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置Seaborn繪圖風(fēng)格
fig, ax = plt.subplots(figsize=(6,6))
flights = sns.load_dataset('flights')
sns.lineplot(data=flights, x='year', y='passengers', ax=ax,
color='xkcd:steel', alpha=0.3, estimator=None)
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
奇怪的是,它怎么和前面的線圖不一樣呢?這里多了很多折線,不是一條平坦的直線?實(shí)際上,指定參數(shù)estimator=None表示沒(méi)有任何估計(jì)量,使用原始數(shù)據(jù)繪圖,而這個(gè)原始數(shù)據(jù)正是這樣子的,同一個(gè)年份對(duì)應(yīng)不同的passengers數(shù)值。而參數(shù)estimator的默認(rèn)值是mean,表示估計(jì)均值,因此上面繪制的圖形中是一個(gè)趨于平坦的直線也是這個(gè)原因。
如果原始數(shù)據(jù)不是這樣子的“分組”重復(fù)性數(shù)據(jù),而是類似時(shí)間序列數(shù)據(jù),那么estimator='mean'和指定為None是沒(méi)有區(qū)別的。Seaborn線圖是一個(gè)例子。
有關(guān)函數(shù)lineplot()的更多參數(shù)用法請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.lineplot.html
下面使用Figure-level的函數(shù)replot()來(lái)繪制線圖,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme() # 設(shè)置默認(rèn)風(fēng)格
tips = sns.load_dataset('tips')
fig = sns.relplot(kind='line', data=tips, x='total_bill', y='tip', hue='smoker',
palette='binary', height=6,aspect=1)
# height指定圖形的高度(英寸),寬度為height*aspect
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
使用Figure層面的繪制線圖函數(shù),盡管是分組線圖,默認(rèn)地也是會(huì)繪制置信帶的,執(zhí)行下面的代碼:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme()
fmri = sns.load_dataset('fmri')
fig = sns.relplot(kind='line', data=fmri, x='timepoint', y='signal', hue='event',
height=6, aspect=1)
plt.show()
程序輸出的結(jié)果見(jiàn)下圖。
其實(shí),使用Axes層面的線圖繪制函數(shù)默認(rèn)條件下也是繪制置信帶的,那為什么上面有一張對(duì)應(yīng)的圖沒(méi)有繪制置信帶呢?
很簡(jiǎn)單,因?yàn)槔L制置信帶需要重復(fù)結(jié)構(gòu)的數(shù)據(jù),也就是說(shuō),在不同的分組條件下,需要在給定的X軸變量值下,有多個(gè)Y軸變量值,但是前者數(shù)據(jù)結(jié)構(gòu)中,當(dāng)分組給定了之后,每一個(gè)年份year值對(duì)應(yīng)一個(gè)乘客數(shù)量passengers。如果不分組,就有多個(gè)對(duì)應(yīng)值了。
下面我們使用第三種方式來(lái)繪制線圖,執(zhí)行下面的代碼:
import seaborn as sns
import seaborn.objects as so
sns.set_theme() # 設(shè)置seaborn繪圖風(fēng)格
fmri = sns.load_dataset('fmri')
(
so.Plot(
fmri, x='timepoint', y='signal', color='region', linestyle='event')
.add(so.Line(color='xkcd:plum',alpha=0.2)).layout(size=(6,6)).show()
)
# 通過(guò)參數(shù)color和alpha來(lái)指定顏色
程序輸出的結(jié)果見(jiàn)下圖。
你可以看到這個(gè)數(shù)據(jù)完全是重復(fù)的,就是說(shuō)在同一個(gè)X軸變量下,Y軸變量值不止一個(gè),它完全繪制了每一個(gè)數(shù)據(jù)點(diǎn)。這里我們沒(méi)有繪制聚合指標(biāo)值,更沒(méi)有繪制置信帶。
函數(shù)so.Line()的更多參數(shù)請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.objects.Line.html
下面的代碼會(huì)增加繪制聚合指標(biāo)值的,比如均值或者方差等等,執(zhí)行下面的代碼:
import seaborn as sns
import seaborn.objects as so
sns.set_theme() # 設(shè)置seaborn繪圖風(fēng)格
fmri = sns.load_dataset('fmri')
(
so.Plot(
fmri, x='timepoint', y='signal', color='region', linestyle='event')
.add(so.Line(color='xkcd:plum',alpha=0.2), so.Agg()).layout(size=(6,6)).show()
)
# so.Agg()默認(rèn)繪制均值
程序輸出的結(jié)果見(jiàn)下圖。
函數(shù)so.Agg()的用法請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.objects.Agg.html
下面我們就繪制標(biāo)準(zhǔn)差置信帶,通過(guò)參數(shù)so.Est()
http://seaborn.pydata.org/generated/seaborn.objects.Est.html
執(zhí)行下面的代碼:
import seaborn as sns
import seaborn.objects as so
sns.set_theme() # 設(shè)置seaborn繪圖風(fēng)格
fmri = sns.load_dataset('fmri')
(
so.Plot
(
data=fmri, x='timepoint', y='signal', color='region', linestyle='event'
)
.add
(
so.Line(color='xkcd:plum',alpha=0.2), so.Agg('std')
)
.add(so.Band(), so.Est(func='std'))
.layout(size=(6,6))
.show()
)
# so.Est()指定估計(jì)量和置信水平,so.Band()繪制置信帶
程序輸出的結(jié)果見(jiàn)下圖。
函數(shù)so.Band()的具體用法請(qǐng)參考這里
http://seaborn.pydata.org/generated/seaborn.objects.Band.html
聯(lián)系客服