1. Matplotlib繪圖簡介
建立在Numpy數組基礎上的多平台數據可視化庫 最初設計用來完善SciPy生態 良好的操作系統兼容性和圖形顯示底層接口兼容性 功能強大,設置靈活
1.1 圖形樣式
所有圖形,可以通過 plt.style.use('classic')
設置圖形樣式,在1.5版本以前只能使用經典⻛格,新版本會有不同的⻛格設置。 1.2 不同環境的使用
不同環境中使用Matplotlib可能稍有不同,需要注意: i. 腳本中會用
在腳本中使用,並不能自動顯示圖形,需要使用 plt.show() 明確讓Matplotlib把圖形顯示出來,否則 不會看到圖形。
ii. IPython shell
在IPython shell中使用畫圖,需要使用魔法命令 %matplotlib , 在以后的畫圖命令中,會自動顯示出需 要畫的圖形。
iii. Jupyter Notebook
在Jupyter Notebook中一般也需要使用魔法函數,但是相應魔法函數有兩個:
%matplotlib inline : 在Notebook中啟動靜態圖形
%matplotlib notebook :在Notebook中啟動交互式圖形
使用以上兩個魔法函數,理論上不需要在使用show函數強制顯示圖形,但在實踐過程中,可能出現不 顯示的情況,此時建議使用
show顯示圖像。
1.3 圖像的保存
如果使用的是交互式顯示圖形,可以直接點擊保存按鈕來保存圖形,在所有代碼中,都可以使用savefig
函數來保存函數。
1.4 兩種不同的畫圖接口
Matplotlib支持兩類畫圖接口:
MATLAB⻛格接口:此類接口的特點是有狀態的,(Stateful),使用方便,對MATLAB用戶友好, 此類接口在pyplot中
面向對象接口:面向對象方式,處理復雜圖形比較方便,能力相對比較強
此兩種⻛格接口比較相似,容易混淆,我們在使用中,經常會混用。
2. 圖形簡單繪制
繪制圖形基本函數是plot, 這個函數的工作原理大概是分別取x,y的值,
然后取到坐標(x,y)后對不同 的連續點進行連線,這樣就形成了一條連續的線,
如果適當調整各個點直接的跨度,就可以看到一條平 滑曲線。
2.1 繪制簡單圖形 需要畫如下簡單線形圖,我們需要創建一個圖形fig和一個坐標軸ax。
fig:figure(plt.Figure)是一個能容納各種坐標軸,圖形,文字和標簽的容器。
ax:axes(plt.Axes)是一個帶有刻度和標簽的矩形,最終會包含各種可視化元素
在圖形繪制中,y=f(x)類函數的顯示可以看做是最簡單的圖形,我們來嘗試.
# 繪制 y=f(x)方程的圖形
# 圖形顯示方式
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# 圖形顯示⻛格 plt.style.use('seaborn-whitegrid')
#創建fig和ax
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 100)
# 顯示sin函數圖形
plt.plot(x, np.sin(x))
#顯示cos函數圖形
plt.plot(x, np.cos(x))
[<matplotlib.lines.Line2D at 0x7fe669654cc0>]
2.2 調整圖形⻛格 通過選用相應的參數,可以調整圖形繪制線條的特征,比如顏色,⻛格等。
圖形顏色值可以支持多種⻛格,常⻅的包括:
名稱: color='red'
顏色代碼: 采用rgbcmyk格式, color=’g'
范圍在0-1的灰度值: color=‘0.85’
十六進制: RGB模式, clolor=’#FFDD45‘
RGB元素,范圍0-1:color=(0.5, 0.2, 0.9)
HTML顏色名稱:color=’chartreuse‘
# 不同顏色的線條
plt.plot(x, np.sin(x-1), color='black')
plt.plot(x, np.sin(x-2), color='y')
plt.plot(x, np.sin(x-3), color='0.65')
plt.plot(x, np.sin(x-4), color='#FF0000')
plt.plot(x, np.sin(x-5), color=(0.2, 1.0, 1.0))
plt.plot(x, np.sin(x-6), color='chartreuse')
[<matplotlib.lines.Line2D at 0x7fe66949ff28>]
同樣,使用linestyle參數可以定制圖形中線的特征,常用的linestyle值為:
solic: 實線,會用 - 做簡寫
dashed:虛線,用 -- 做簡寫
dashdot:點划線, 用 -. 簡寫
dotted:實心點線, 用 : 簡寫
這幾個是比較常用的,所有類型可以通過內置文檔進行查看。
# 不同顏色的線條
plt.plot(x, np.sin(x-1), linestyle='solid', color='black')
plt.plot(x, np.sin(x-2),linestyle='--', color='y')
plt.plot(x, np.sin(x-3), linestyle='dashdot',color='0.65')
plt.plot(x, np.sin(x-4), linestyle=':',color='#FF0000')
[<matplotlib.lines.Line2D at 0x7fe669478748>]
linestyle和color可以組合在一起使用更簡潔的表示形式,plot函數提供了一個非關鍵字參數可以讓我們 使用組合簡寫:
# 使用組合簡寫
plt.plot(x, x+0, '-r')
plt.plot(x, x+1, '--g')
plt.plot(x, x+2, '-.b')
plt.plot(x, x+3, ':c')
[<matplotlib.lines.Line2D at 0x7fe6693a7550>]
2.3 調整坐標軸 i. xlim和ylim
Matplotlib會自動為圖形調整坐標軸上下限,但有時候也需要自定義調整,常用的調整方法是:
plt.xlim: x軸
plt.ylim: y軸
通過xlim和ylim可以調整x軸y軸的上下限,需要說明的是,這兩個函數只是簡單的把坐標軸數據改成兩 個參數之間的值就可以,它並不關心真正設置的值,比如可以設置逆序。
# 手動設置坐標軸
# 考慮到x的取值,我們得到了一個很丑很不協調的sin plt.plot(x, np.sin(x))
plt.xlim(-5,10)
plt.ylim(-3,5)
(-3, 5)
ii. axis函數
axis函數可以更靈活更強大的設置坐標軸信息, 可以傳入 [xmin, xmax, ymin, ymax] 來設置x,y軸
的四個值,也還可以設置坐標軸的⻛格,比如:
tight:把圖形設置成緊湊模式,即坐標按照圖形內容自動收緊坐標軸,不留下空白區域。
equal:圖形顯示分辨率為1:1
# 手動設置坐標軸
plt.plot(x, np.cos(x)) plt.axis([-5,10,-3,5])
[-5, 10, -3, 5]
# 讓圖形自動緊湊
# 圖形空白自動去掉
plt.plot(x, np.cos(x))
plt.axis('tight')
(0.0, 10.0, -0.9999471661761239, 1.0)
# 讓圖形自動緊湊
# 顯示分辨率1:1
plt.plot(x, np.cos(x))
plt.axis('equal')
(0.0, 10.0, -1.0, 1.0)
2.4 設置圖形標簽 在對圖形進行設置的時候,可能需要一些文字性信息,此類信息主要包含:
圖形標題:plt.title
坐標軸標題: plt.xlabel, plt.ylabel 簡易圖例: plt.legend
對此類信息的設置,中文可能會出現亂碼,需要對jupyter Notebook進行單獨設置。 i. 簡單標簽和title設置
# 設置sin圖形標簽
plt.plot(x, np.sin(x ))
plt.title("sin Function")
plt.xlabel("X-Value")
plt.ylabel("Y-Value")
Text(0,0.5,'Y-Value')
ii. 簡單圖例設置
通過legend可以設置圖例,同時通過參數的調整可以細膩的設置圖例的位置,形式等。 常⻅的參數為:
loc: 圖例位置
frameon:是否帶邊框
framealpha: 顏色透明
shadow: 陰影
#使用面向對象的方法畫圖
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x ), color='red', label="SIN")
ax.plot(x, np.cos(x ), color='blue', label="COS")
#全部使用默認 ax.legend()
<matplotlib.legend.Legend at 0x7fe65abe54e0>
#使用面向對象的方法畫圖
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x ), color='red', label="SIN")
ax.plot(x, np.cos(x ), color='blue', label="COS")
#更改位置,添加邊框
ax.legend(loc='upper left', frameon=True)
<matplotlib.legend.Legend at 0x7fe65ab9ca58>
#使用面向對象的方法畫圖
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x ), color='red', label="SIN")
ax.plot(x, np.cos(x ), color='blue', label="COS")
#更改位置,添加邊框
ax.legend(loc='upper left', frameon=True, shadow=True, framealpha=0.2)
<matplotlib.legend.Legend at 0x7fe65a834da0>
iii. 選擇圖例顯示的元素 選擇圖例顯示元素一般有兩種方法:
通過設置圖形的label屬性,不設置的不顯示 通過給legend傳遞需要顯示的圖形,不傳遞的不顯示
# 有時候可能我們並不想把所有線條的圖例都顯示出來,此時可以選擇圖例顯示的元素
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
sin_line = ax.plot(x, np.sin(x ), color='red', label="SIN")
cos_line = ax.plot(x, np.cos(x ), color='blue', label="COS")
#明確把需要添加圖例的線條放入legend作為參數
#沒有添加的不顯示
ax.legend(cos_line, loc='upper left', frameon=True, shadow=True, framealpha=0.2)
<matplotlib.legend.Legend at 0x7fe65a6f97f0>
# 有時候可能我們並不想把所有線條的圖例都顯示出來,此時可以選擇圖例顯示的元素
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
#默認legend只顯示有label的線條,沒有的不顯示
sin_line = ax.plot(x, np.sin(x ), color='red', label="SIN")
cos_line = ax.plot(x, np.cos(x ), color='blue')
#只有一個具有label參數,沒有的就不顯示
ax.legend(loc='upper left', frameon=True, shadow=True, framealpha=0.2)
<matplotlib.legend.Legend at 0x7fe65a64df98>
iv. 圖例中顯示不同尺寸
# scatter用來畫散點圖 # 我們將在后面章節中講述
rng = np.random.RandomState(0)
x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
# 設定橫軸坐標的范圍
plt.xlim(-3, 6)
#畫散點圖
plt.scatter(x, y, c=colors, s=sizes, alpha=0.4, cmap='viridis')
#顯示顏色條
plt.colorbar()
#畫圖例散點圖
for a in [0.1, 0.3, 0.5, 0.7, 0.9]:
plt.scatter([], [], c='red', alpha=0.5, s=a*300, label="{} Label".format(a))
#畫圖例文字
plt.legend(scatterpoints=1, frameon=False, labelspacing=1, title='Random Value')
<matplotlib.legend.Legend at 0x7fe659c3dba8>
2.5 配置顏色條 使用顏色條來配置圖例是一種常規操作, 本章講述顏色條的配置。
i. 簡單顏色條配置
# 准備數據
import matplotlib.pyplot as plt import numpy as np
plt.style.use('classic')
%matplotlib inline
x = np.linspace(0,10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])
plt.imshow(I)
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7fe659b681d0>
ii. 配置顏色條
可以通過cmap參數為圖形設置顏色條的配置方案, 所有配色方案都在
plt.cm命名空間里,可以直接通過 plt.cm.<TAB> 查看。
選擇合理的配色方案能讓實行示例清晰明了,常⻅的配色方案有:
順序配色方案: 由一組連續的顏色構成的方案,例如binary或者viridis
互逆配色方案: 由兩種互補的顏色構成,表示正反兩種含義,例如RdBu或者PuOr
定性配色方案:隨機順序的一組顏色,例如rainbow或者jet
#使用灰色顏色條
x = np.linspace(0,10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])
plt.imshow(I, cmap='RdBu')
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7fe659eca5c0>
iii. 離散型顏色條 顏色條默認是連續的,可以通過設置配色方案和顏色的區間量來顯示離散型顏色條。
#使用灰色顏色條
x = np.linspace(0,10, 1000)
I = np.sin(x) * np.cos(x[:, np.newaxis])
#get_cmap兩個參數
# 1. 配色方案
# 2. 顏色多少等分
c = plt.cm.get_cmap("PuOr", 10)
plt.imshow(I, cmap=c)
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7fe6595ac5c0>
3. 散點圖
散點圖(Scatter Plot)主要是以點為主,數據是不連續的數據,通過設置線的型號為原點來完成。
其余的線的形狀為:
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
- '1' tri_down marker
- '2' tri_up marker
- '3' tri_left marker
- '4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
3.1 簡單散點圖
#准備環境
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# 設置⻛格 plt.style.use('seaborn-whitegrid')
x = np.linspace(0,10, 30) y = np.sin(x)
# 通過設置線型為點來完成三點圖的顯示 plt.plot(x, y, 'o', color='blue')
[<matplotlib.lines.Line2D at 0x7fe668f962b0>]
3.2 其他散點圖形狀
# 散點圖的形狀展示
rng = np.random.RandomState(0)
for marker in ['o', '.', 'x', '+', '^', '<', 's', 'd']: plt.plot(rng.rand(5), rng.rand(5), marker, label='marker=
{}'.format(marker)) plt.legend(numpoints=1) plt.xlim(0, 1.8)
3.3 點線結合的圖
在plot的使用中,對線的類型使用直線(-),圓圈(o)可以畫出帶有點線結合的圖形。
x = np.linspace(0,10, 30) y = np.sin(x)
# 通過設置線型為點來完成三點圖的顯示
plt.plot(x, y, '-o', color='blue')
[<matplotlib.lines.Line2D at 0x7fe6692aa748>]
3.4 使用plt.scatter畫散點圖
另一個畫散點圖的函數是scatter,用法和plot函數類似。
但scatter更加靈活,甚至可以單獨控制每個散點不同的屬性,例如大小,顏色,邊控等。
相對來講,對於大量數據的渲染,plot效率要高於scatter。
# scatter案例
rng = np.random.RandomState(0) x = rng.randn(100)
y = rng.randn(100)
colors = rng.rand(100)
sizes = 1000 * rng.rand(100)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.4, cmap='viridis')
#顯示顏色條 plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7fe668405438>
4. 誤差線 通過對誤差線的繪制,可以直觀反映出數據的誤差大小等。
#准備環境
%matplotlib inline
import matplotlib.pyplot as plt import numpy as np
# 設置⻛格 plt.style.use('seaborn-whitegrid')
4.1 基本誤差線
誤差線使用函數plt.errorbar來創建,可以使用不同的參數進行配置。
ecolor: 控制誤差線顏色
fmt:線型,代碼與plot線型控制參數一致
# 基本誤差線
x = np.linspace(0, 10, 50)
dy = x * 0.7
y = np.sin(x) + dy
plt.errorbar(x, y, yerr=dy, fmt='.k', ecolor='blue')
<ErrorbarContainer object of 3 artists>
x = np.linspace(0, 10, 50) dy = 0.7
y = np.sin(x) + dy * np.random.rand(50)
plt.errorbar(x, y, yerr=dy, fmt='o', ecolor='blue', color='red', elinewidth=3, capsize=1)
<ErrorbarContainer object of 3 artists>
4.2 連續誤差 連續誤差表示的是連續量,沒有比較合適的簡單方法來繪制此類型圖形,我們可以使用plt.plot和
plt.fill_between來解決,即畫出兩條區間線表示上下限,然后填充中間區域即可。
下面我們對sin和cos進行簡單繪制,繪制后填充兩個的中間差值。
x = np.linspace(0,10, 50) ysin = np.sin(x)
ycos = np.cos(x)
plt.plot(x, ysin, color='red')
plt.plot(x, ycos, color='blue')
plt.fill_between(x, ysin, ycos, color='gray', alpha=0.2)
<matplotlib.collections.PolyCollection at 0x7fe65b2eb860>
5. 密度圖和等高線
等高線或者密度圖使我們常用圖形, Matplotlib提供三個函數來供我們使用:
plt.contour: 等高線
plt.contourf: 自帶填充色
plt.imshow: 顯示圖形
具體使用請參照下面例子:
#准備環境
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# 設置⻛格 plt.style.use('seaborn-whitegrid')
i. contour
我們需要一個三維函數,z=f(x,y)來演示等高線圖,按照下面函數來進行生成.
contour創建需要至少三個參數,x,y和z,其中x,y我們可以用橫軸縱軸表示,z用等高線來表示就可
以。當只有一個顏色的圖形是,虛線表示負值,實現部分表示正值。
我們使用meshgrid來從一維數據構成二維網格數據。
#函數
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y*x) * np.cos(x)
x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40)
#得到網格點矩陣
x, y = np.meshgrid(x, y)
# 計算z軸的值 z = f(x,y)
#繪制圖形
plt.contour(x, y, z, colors='green')
<matplotlib.contour.QuadContourSet at 0x7fe65b22bda0>
#繪制圖形
#使用紅灰色配色方案
#把值范圍50等分
plt.contour(x, y, z, 50, cmap='RdGy')
<matplotlib.contour.QuadContourSet at 0x7fe65b190550>
ii. plt.contourf
以上繪圖還是存在比如間隙過大的問題,我們可以用連續的顏色來填充圖形,讓它變的平滑起來。
plt.contourf可以滿足我們的需求,其余填充參數基本同plt.contour一致。
<matplotlib.contour.QuadContourSet at 0x7fe65b017908>
iii. plt.imshow
#繪制圖形
#平滑過度色彩
plt.contourf(x, y, z, 50, cmap='RdGy')
上述圖形的顯示色彩過度還是不夠細膩,因為畫上面的圖的時候使用的是一條一條的線來繪制,
雖然可 以通過縮小間隙來讓圖形更加細膩,但是這樣會造成計算資源的過度浪費,
Matplotlib為我們提供了 imshow來完成漸變圖的渲染。
plt.imshow函數不支持x,y軸的設置,必須通過extent參數來完成設置,extent=[xmin, xmax, ymin, ymax]
plt.imshow默認以右上⻆為坐標原點,一般我們使用左下⻆為坐標原點 plt.imshow自動調整坐標軸精度來適配數據顯示,可以通過plt.axis(aspect='image')來設置x,y的 單位
# imshow
plt.imshow(z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy')
plt.colorbar()
plt.axis(aspect='image')
(0.0, 5.0, 0.0, 5.0)
# 顯示等高線的同時通過顏色顯示內容
contours = plt.contour(x, y, z, 3, colors="green")
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(z, extent=[0, 5, 0, 5], origin='lower', cmap='RdGy', alpha=0.2)
plt.colorbar() plt.axis(aspect='image')
(0.0, 5.0, 0.0, 5.0)
6. 頻次直方圖,數據區間划分和分布密度
#准備環境
%matplotlib inline
import matplotlib.pyplot as plt import numpy as np
# 設置⻛格 plt.style.use('seaborn-whitegrid')
i. 頻次直方圖 使用plt.hist可以畫直方圖,重要的參數有:
bins: 畫幾條方圖
color: 顏色
alpha: 透明度
histtype: 圖類型
data = np.random.randn(1000)
plt.hist(data)
(array([ 9., 44., 108., 178., 241., 194., 134., 67., 20., 5.]), array([-2.83511303, -2.23919796, -1.64328288, -1.04736781, -0.45145274, 0.14446234, 0.74037741, 1.33629248, 1.93220755, 2.52812263,
3.1240377 ]),
<a list of 10 Patch objects>)
plt.hist(data, bins=30, alpha=0.3, histtype='stepfilled', color='steelblue', edgecolor='none')
(array([ 2., 4., 3., 9., 19., 16., 30., 32., 46., 52., 52., 74., 77., 87., 77., 83., 66., 45., 56., 41., 37., 29., 18., 20., 8., 7.,
5., 3., 0., 2.]),
array([-2.83511303, -2.63647467, -2.43783631, -2.23919796, -2.0405596 ,
-1.84192124, -1.64328288, -1.44464453, -1.24600617, -1.04736781, -0.84872945, -0.6500911 , -0.45145274, -0.25281438, -0.05417602, 0.14446234, 0.34310069, 0.54173905, 0.74037741, 0.93901577, 1.13765412, 1.33629248, 1.53493084, 1.7335692 , 1.93220755, 2.13084591, 2.32948427, 2.52812263, 2.72676099, 2.92539934,
3.1240377 ]),
<a list of 1 Patch objects>)
#更復雜的案例
x1 = np.random.normal(0, 0.8, 1000) x2 = np.random.normal(-2, 1, 1000) x3 = np.random.normal(3,2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, bins=40)
plt.hist(x1, **kwargs) plt.hist(x2, **kwargs) plt.hist(x3, **kwargs)
(array([ 1., 0., 1., 2., 5., 2., 6., 5., 8., 11., 17., 23., 26., 32., 35., 53., 67., 49., 50., 53., 61., 58., 67., 67., 53., 45., 53., 32., 34., 19., 25., 22., 9., 2., 4., 1., 0., 1., 0.,
1.]),
array([-3.90483644, -3.575889 , -3.24694156, -2.91799412, -2.58904668,
-2.26009924, -1.9311518 , -1.60220436, -1.27325692, -0.94430948, -0.61536204, -0.2864146 , 0.04253285, 0.37148029, 0.70042773, 1.02937517, 1.35832261, 1.68727005, 2.01621749, 2.34516493, 2.67411237, 3.00305981, 3.33200725, 3.66095469, 3.98990213, 4.31884957, 4.64779701, 4.97674445, 5.30569189, 5.63463934, 5.96358678, 6.29253422, 6.62148166, 6.9504291 , 7.27937654, 7.60832398, 7.93727142, 8.26621886, 8.5951663 , 8.92411374,
9.25306118]),
<a list of 1 Patch objects>)
ii. 二維頻次直方圖和數據區間划分
# 准備數據 mean = [0, 0]
cov = [[1,1], [1,2]]
# 多元正太分布隨機樣本抽取
# mean:多元正態分布的維度
# cov:多元正態分布的協方差矩陣,且協方差矩陣必須是對稱矩陣和半正定矩陣(形狀為(N,N)的二維數 組)。
# size: 數組的形狀(整數或者由整數構成的元組)。如果該值未給定,則返回單個N維的樣本(N恰恰是 上面mean的⻓度)。
x, y = np.random.multivariate_normal(mean, cov, 10000).T
i. plt.hist2d
使用plt.hist2d可以畫二維直方圖。
plt.hist2d(x, y, bins=30, cmap='Blues') cb = plt.colorbar() cb.set_label("counts in bin")
ii. plt.hexbin
hist2d是用的方塊組成的圖形,還可以使用六邊形進行圖形分割,需要使用plt.hexbin來完成,用來將 圖形化成六⻆形的蜂窩。
iii. 核密度估計
核密度估計(KernelDensityEstimation)是一種常用的評估多維度分布密度的方法, 本節主要是對畫圖函 數做一個展示,不詳細講述
kde算法。
kde方法通過不同的平滑帶寬⻓度在擬合函數的准確性和平滑性之間做出一種權衡。
plt.hexbin(x, y, gridsize=30, color='red')
cb = plt.colorbar(label="count in bin")
from scipy.stats import gaussian_kde
data = np.vstack([x, y])
kde = gaussian_kde(data)
x = np.linspace(-3.5, 3.5, 40)
y = np.linspace(-6, 6, 40)
x, y = np.meshgrid(x, y)
z = kde.evaluate(np.vstack([x.ravel(), y.ravel()]))
plt.imshow(z.reshape(x.shape), origin='lower', aspect='auto', extent=[-3.5, 3.5, -6, 6], cmap='Blues')
cb = plt.colorbar()
cb.set_label("density")
7. 多子圖 一個界面上有時候需要出現多張圖形,這就是多子圖。
Matplotlib提供了subplot的概念,用來在較大的圖形中同時放置較小的一組坐標軸,
這些子圖可能是畫 中畫,網格圖,或者更復雜的布局形式。
# 准備數據
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("seaborn-white")
7.1 手動創建多子圖
7.1 手動創建多子圖
創建坐標軸最基本的方法是用plt.axes函數, 通過設置不同的坐標參數,可以用來手工創建多子圖。
多子圖坐標系統可以使用四個元素列表,[left, button, width, height],分別是:
bottom: 底部坐標 left:左側坐標 width: 寬度 height: 高度
其中數值的取值范圍是0-1, 左下⻆為0.
[0.5, 0.2, 0.3, 0.4]代表從下面開始50%,從左開始20%的地方是圖形的左下⻆,圖形寬高占用30%和 40%。
#Matlab⻛格
ax1 = plt.axes()
ax2 = plt.axes([0.4, 0.2, 0.3, 0.6])
#面向對象格式
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2))
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))
[<matplotlib.lines.Line2D at 0x7fc8b5147748>]
7.2 plt.subplot 建議網格子圖
plt.subplot可以創建整⻬排列的子圖,這個函數有三個整形參數:
子圖行數
子圖列數
索引值: 索引值從1開始,左上⻆到右下⻆逐漸增大
# matlab⻛格
for i in range(1,7):
plt.subplot(2,3,i)#行、列、索引
plt.text(0.5, 0.5, str((2,3,i)), fontsize=18, ha='center')
#面向對象⻛格
# plt.subplots_adjust調整子圖間隔
# plt.add_subplot
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1,7):
ax = fig.add_subplot(2,3,i)
ax.text(0.5, 0.5, str((2,3,i)), fontsize=18, ha='center')
7.3 plt.subplots
一次性創建多個子圖,主要四個參數:
行數
列數
sharex:是否共享x軸
sharey:是否共享y軸
下圖使用subplots創建2x3個子圖,每一行共享y軸,每一列共享x軸。
函數返回值是一個NumPy數組,可以通過下表訪問返回的每一個子圖。
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
for i in range(2):
for j in range(3):
ax[i,j].text(0.5, 0.5, str((i,j)), fontsize=18, ha='center')
fig
7.4 plt.GridSpec
利用plt.GridSpec可以用來實現更復雜的多行多列子圖網格。
這種畫圖方式跟前端網⻚技術的網格思想 類似,
需先用 plt.GridSpec指出需要總共划分的行和列,然后在具體的畫相應子圖的時候指出一個子圖需要占用的網 格。
# 畫圖方式
grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
plt.subplot(grid[0,0]) plt.subplot(grid[0,1:]) plt.subplot(grid[1,:2]) plt.subplot(grid[1,2])
<matplotlib.axes._subplots.AxesSubplot at 0x7fc8b4d7db00>
# 正態分布數據的多子圖顯示
mean = [0,0]
cov = [[1,1], [1,2]]
x, y = np.random.multivariate_normal(mean, cov, 3000).T
#設置坐標軸和網格配置
fig = plt.figure(figsize=(6,6))
grid = plt.GridSpec(4,4, hspace=0.2, wspace=0.2)
main_ax = fig.add_subplot(grid[:-1, 1:])
y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax) x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)
# 主軸坐標畫散點圖
main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)
# 次軸坐標畫直方圖
x_hist.hist(x, 40, histtype='stepfilled', orientation='vertical', color='red')
x_hist.invert_yaxis()
y_hist.hist(x, 40, histtype='stepfilled', orientation='horizontal', color='blue')
x_hist.invert_xaxis()
8. 文字與注釋
8.1 坐標變換和文字位置
通過不同的坐標變換,可以把文字放在不同的位置,文字的坐標變換方法有:
ax.transData:以數據為基准的坐標變換 ax.transAxes: 以軸為基准
#環境准備
%matplotlib inline
import matplotlib.pyplot as plt import numpy as np
plt.style.use("seaborn-whitegrid")
fig, ax = plt.subplots(facecolor='lightgray')
ax.axis([0, 10, 0, 10])
ax.text(1, 5, "Data:(1,5)", transform=ax.transData) #這里是關於數據的,取1,5這一個點
ax.text(0.5, 0.1, "Axes:(0.5, 0.1)", transform=ax.transAxes) #這里是關於軸的,取50%x軸10%y軸
Text(0.5,0.1,'Axes:(0.5, 0.1)')
8.2 箭頭和注釋 帶箭頭的注釋一般可以使用兩個函數實現:
plt.arrow: 產生SVG向量圖形式的箭頭,會隨着分辨率改變而變換,不推薦
plt.annotate: 可以創建文字和箭頭
在annotate中,箭頭的⻛格通過arrowprops參數控制,具體參數含義使用的時候可以參考官方文檔。
fig, ax = plt.subplots()
x = np.linspace(0, 20, 1000)
ax.plot(x, np.cos(x))
ax.axis('equal')
ax.annotate("local maximum", xy=(6.28, 1), xytext=(10, 4), \ arrowprops=dict(facecolor='black',shrink=0.05 ))
ax.annotate('local minimum', xy=(5 * np.pi, -1), xytext=(2, -6),\ arrowprops=dict(arrowstyle="->", connectionstyle='angle3, angleA=0,
angleB=-90'))
Text(2,-6,'local minimum')
8.3 自定義坐標軸刻度
Matplotlib有默認的坐標軸定位器(locator)和格式生成器(formatter),基本需求可以滿足,但是如果需
要定制更細膩的表現,需要用到其他的東⻄。
Matplotlib畫圖的基本原理是:
figure對象可以看做是一個圖形的總的容器,里面可以包含幾個子圖
axes:每個figure包含一個或者多個axes,每個axes有包含其他表示圖形內容的對象
每個axes有xaxis和yaxis屬性,每個屬性包含坐標軸的線條,刻度,標簽等屬性
i. 主要刻度和次要刻度
通過一下案例,我們發現主要和次要刻度標簽都是通過LogLocater對象設置的, 同樣格式生成器都是 LogFormatterSciNotaion對象。
ax = plt.axes(xscale='log', yscale='log')
print(ax.xaxis.get_major_locator())
print(ax.xaxis.get_minor_locator())
print(ax.xaxis.get_major_formatter())
print(ax.xaxis.get_minor_formatter())
<matplotlib.ticker.LogLocator object at 0x7fd697b69c50> <matplotlib.ticker.LogLocator object at 0x7fd697b69a58> <matplotlib.ticker.LogFormatterSciNotation object at 0x7fd697b69a90> <matplotlib.ticker.LogFormatterSciNotation object at 0x7fd697be4a58>
ii. 隱藏刻度和標簽 有時候我們不需要總顯示刻度和標簽,可以通過設置空的刻度標簽和格式化生成器完成。
# 刪除locator和formmater
ax = plt.axes()
ax.plot(np.random.rand(50))
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_formatter(plt.NullFormatter())
iii. 增減刻度數量
使用plt.MaxNLocator可以設置最多需要顯示多少刻度,根據設置的刻度數量,Matplotlib會自動為刻 度安排恰當的位置。
# 一下圖例使用默認刻度,但顯得過於擁擠
fig, ax = plt.subplots(4, 4, sharex=True, sharey=True)
for axi in ax.flat: axi.xaxis.set_major_locator(plt.MaxNLocator(3)) axi.yaxis.set_major_locator(plt.MaxNLocator(3))
fig
iv. 花哨的刻度格式
使用MultipleLocator可以實現把刻度放在你提供的數值的倍數上。
fig, ax = plt.subplots()
x = np.linspace(0, 3*np.pi, 100)
ax.plot(x, np.sin(x), lw=3, label='SIN')
ax.plot(x, np.cos(x), lw=3, label='COS')
#設置網格,圖例和坐標軸上下限
ax.grid(True)
ax.legend(frameon=False)
ax.axis('equal')
ax.set_xlim(0, 3*np.pi)
(0, 9.42477796076938)
ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi/2))
ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi/4))
fig
v. 定位器和格式生成器常用值 定位器和格式生成器常用的取值在plt命名空間內可以找到,下面列出來:
NullLocator: 無刻度
FixedLocator:刻度位置固定
IndexLocator:用索引做定位器,例如x=range(10)
LinearLocator: 從min到max均勻分布
LogLocator: 從min到max對數分布
MultipleLocator: 刻度和范圍是基數的倍數
MaxNLocator: 為最大刻度找到最優位置
AutoLocator: 以MaxNlocator進行簡單配置
AutoMinorLocator:次要刻度的定位器
格式生成器的取值:
NullFormatter: 刻度上無標簽
IndexFormatter: 將一組標簽設置為字符串
FixedFormatter: 手動設置標簽
FuncFormatter:自定義函數設置標簽
FormatStrFormatter:為每個刻度設置字符串格式
ScalarFormatter: 為標量值設置標簽
LogFormatter: 對數坐標軸的默認格式生成器
9. 配置文件和樣式表
Matplotlib允許手動調整默認樣式,如果默認拍照不能滿足的情況下,可以手動調整樣式。
9.1 手動配置圖形 通過手動配置圖形,可以改變圖形的刻度,北京等內容,下面例子是對圖形配置的一個簡單示例。
#設置環境
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')
%matplotlib inline
#使用默認配置顯示圖形
x = np.random.randn(1000)
plt.hist(x)
(array([ 1., 3., 43., 119., 237., 285., 195., 92., 22., 3.]), array([-3.90095153, -3.1706347 , -2.44031787, -1.71000103, -0.9796842 , -0.24936737, 0.48094946, 1.2112663 , 1.94158313, 2.67189996,
3.40221679]),
<a list of 10 Patch objects>)
# 對圖形進行各種配置
ax = plt.axes()
ax.set_axisbelow(True)
#被色網格線
plt.grid(color='g', linestyle='solid')
#隱藏坐標的線條
for spine in ax.spines.values():
spine.set_visible(False)
#隱藏上邊和右邊的刻度
ax.xaxis.tick_bottom()
ax.yaxis.tick_left()
#弱化刻度和標簽
ax.tick_params(colors='green', direction='out')
for tick in ax.get_xticklabels():
tick.set_color('orange')
for tick in ax.get_yticklabels():
tick.set_color('orange')
#設置頻次直方圖輪廓色和填充色
ax.hist(x, edgecolor="#1122FF", color='#998877')
(array([ 1., 3., 43., 119., 237., 285., 195., 92., 22., 3.]), array([-3.90095153, -3.1706347 , -2.44031787, -1.71000103, -0.9796842 , -0.24936737, 0.48094946, 1.2112663 , 1.94158313, 2.67189996,
3.40221679]),
<a list of 10 Patch objects>)
9.2 修改默認配置
#保存默認的配置,修改后需要還原
rc_default = plt.rcParams.copy()
from matplotlib import cycler
colors = cycler('color', ['#777777', '#888888', '#999999', '#AAAAAA', '#BBBBBB', '#CCCCCC'])
plt.rc('axes', facecolor='#EEEEEE', edgecolor='none', \ axisbelow=True, grid=True, prop_cycle=colors)
plt.rc('grid', color='w', linestyle='solid')
plt.rc('xtick', direction='out', color='gray')
plt.rc('ytick', direction='out', color='gray')
plt.rc('patch', edgecolor='green')
plt.rc('lines', linewidth=2)
plt.hist(x)
(array([ 1., 3., 43., 119., 237., 285., 195., 92., 22., 3.]), array([-3.90095153, -3.1706347 , -2.44031787, -1.71000103, -0.9796842 , -0.24936737, 0.48094946, 1.2112663 , 1.94158313, 2.67189996,
3.40221679]),
<a list of 10 Patch objects>)
for i in range(4):
plt.plot(np.random.rand(10))
plt.rcParams.update(rc_default) #把原來的配置還原下來了
9.3 樣式表 在style模塊里,包含大量樣式表可以使用。
使用 plt.style.available 可以得到所有可用的樣式:
['seaborn-dark', 'tableau-colorblind10', 'fivethirtyeight', 'seaborn-white', 'seaborn-bright', 'seaborn-deep', 'ggplot', 'Solarize_Light2', 'seaborn- colorblind', 'seaborn-darkgrid', 'seaborn-pastel', 'seaborn', 'seaborn-talk', '_classic_test', 'seaborn-notebook', 'dark_background', 'fast', 'seaborn-dark- palette', 'classic', 'grayscale', 'seaborn-poster', 'bmh', 'seaborn-ticks', 'seaborn-whitegrid', 'seaborn-paper', 'seaborn-muted']
對樣式的使用,可以使用代碼 plt.style.use('stylename') 來處理。
但這個會改變以后所有的⻛ 格,如果需要,建議使用⻛格上下文管理器來臨時更換:
plt.style.context('stylename')
# 准備數據
def hist_and_lines():
np.random.seed(0)
fig, ax = plt.subplots(1,2,figsize=(11,4)) ax[0].hist(np.random.randn(1000))
for i in range(3):
ax[1].plot(np.random.rand(10))
ax[1].legend(['a', 'b', 'c'], loc='lower left')
i. 默認⻛格
#還原默認⻛格
plt.rcParams.update(rc_default)
hist_and_lines()
ii. FiveThirtyEight⻛格 這個⻛格是模仿網站FiveThirtyEight。
http://fivethirtyeight.com
with plt.style.context('fivethirtyeight'):
hist_and_lines()
iii. ggplot⻛格 ggplot是R語言非常流行的可視化工具,ggplot⻛格就是模仿ggplot工具包。
with plt.style.context('ggplot'):
hist_and_lines()
iv. bmh⻛格
with plt.style.context('bmh'):
hist_and_lines()
v. 黑色背景⻛格
with plt.style.context("dark_background"):
hist_and_lines()
vi. 灰度⻛格
with plt.style.context("grayscale"):
hist_and_lines()
vii. Seaborn⻛格
# 導入seaborn庫的時候自動導入seaborn⻛格
import seaborn
hist_and_lines()
10. 三維圖 借助於matplotlib自帶的mplot3d包,我們可以實現三維圖的繪制。
我們默認使用魔法函數 matplotlib inline 來進行繪制,但是,如果使用魔法函數 %matplotlib notebook 繪制,畫出的圖是交互式的,我們可以通過拖動圖形來讓圖形轉動。
10.1 簡單三維坐標的繪制
通過導入mplot3d包,在 plt.axes 中使用projection參數,我們可以采用默認方式繪制一個三維的坐 標系。
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection='3d')
10.2 三維數據的點和線
三維數據主要研究的是 z=f(x,y) , 如果繪制三維圖形,需要有x,y,z,求三個數據然后在相應的點上 畫點或者連線。
使用的畫點或者連線的函數常用的是 ax.plot3d 和 ax.scatter3D 。
為了呈現更好的三維效果,默認散點圖會自動改變透明度。
# 畫一個螺旋三維線
%matplotlib inline
ax = plt.axes(projection='3d')
#數據准備
z = np.linspace(0,15, 1000)
x = np.sin(z)
y = np.cos(z)
#三維線
ax.plot3D(x, y, z, 'red')
#三維點
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens')
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x7f5014234748>
10.3 三維等高線
三維圖默認的觀察視⻆可能不是最后的,我們可以時候用 ax.view_init 來改變觀察視⻆,兩個參數:
俯仰⻆度,即x-y平面的旋轉⻆度 方位⻆度,即沿着z軸順時針轉動⻆度
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X,Y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50)
ax.set_xlabel("X-Axis")
ax.set_ylabel("Y-Axis")
ax.set_zlabel("Z-Axis")
Text(0.5,0,'Z-Axis')
# 上圖調整旋轉⻆度為(60, 30)
ax.view_init(60, 30)
fig
10.4 線框圖和曲面圖
有網格做成的可視化三維圖。線框圖顯示的是由線條組成的輪廓,相對來講,曲面圖是有多邊形構成的 多邊形,可以更好的
顯示圖形表面的結構。
如果選擇合適的坐標系,利用合適的數據區間,可以產生類似切片的可視化效果。
fig = plt.figure()
ax = plt.axes(projection='3d')
#線框圖
ax.plot_wireframe(X, Y, Z, color='red')
ax.set_title('wireframe')
ax.view_init(60, 30)
fig = plt.figure()
ax = plt.axes(projection='3d')
#線框圖
ax.plot_surface(X, Y, Z, color='green')
ax.set_title('surface')
ax.view_init(60, 30)
r = np.linspace(0, 6, 30)
theta = np.linspace(-0.9*np.pi, 0.8*np.pi, 40)
r, theta = np.meshgrid(r, theta)
X = r * np.sin(theta)
Y = r * np.cos(theta) Z = f(X, Y)
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.view_init(60,-40)
10.5 曲面三⻆剖分
對於一些要求均勻采樣的網格數據顯得太過嚴格而不太容易實現的圖像,我們可以使用三⻆剖分 (triangulation-based plot)來解決。
# 隨機散點數據組成的圖形
theta = 2 * np.pi * np.random.random(1000)
r = 6 * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax = plt.axes(projection='3d')
ax.scatter(x, y, z, c=z, cmap='viridis', linewidth=1)
ax.view_init(60, 30)
#隨機數據構成三⻆剖分
ax = plt.axes(projection='3d')
ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
ax.view_init(60, 30)
11. Seaborn做數據可視化
Matplotlib作為數據可視化工具非常強大,但相對來講,還是有一些缺憾,特別是早期版本,引發問題 的根本原因主要是,Matplotlib開發早於Pandas,所以前期版本對Pandas的支持可想而知不會太好, 相比較而言,Seaborn作為在Matplotlib基礎上發展出來的繪圖工具,快速得到使用和的認可。
11.1 Seaborn和Matplotlib的對比 同一組數據我們用Seaborn和Matplotlib兩種繪圖⻛格來繪圖進行對比。
# 准備環境
%matplotlib inline
import matplotlib.pyplot as plt import numpy as np
import pandas as pd
plt.style.use("classic")
# 准備數據
rng = np.random.RandomState(0)
x = np.linspace(0, 10, 500)
y = np.cumsum(rng.randn(500, 6), 0)
#畫圖
plt.plot(x, y)
plt.legend("ABCDEF", ncol=2, loc='upper left')
<matplotlib.legend.Legend at 0x7f4ff8e5f9e8>
# 上述圖用seaborn來實現
import seaborn as sns
sns.set()
plt.plot(x, y)
plt.legend("ABCDEF", ncol=2, loc='upper left')
<matplotlib.legend.Legend at 0x7f50147832b0>
11.2 Seaborn圖形介紹 Seaborn的主要思想是用高級命令為統計數據探索和統計模型擬合創建各種圖形。
i. 頻次直方圖,KDE和密度圖
# 直方圖
data = np.random.multivariate_normal([0, 0], [[5, 2], [2, 2]], size=2000)
data = pd.DataFrame(data, columns=['X', 'Y'])
for col in 'XY': plt.hist(data[col], alpha=0.5)
# sns.kedplot可以實現KDE變量帆布的平滑估計
for col in 'XY':
sns.kdeplot(data[col], shade=True)
/sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
# distplot可以讓頻次直方圖和KDE結合起來
sns.distplot(data['X'])
sns.distplot(data['Y'])
/sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<matplotlib.axes._subplots.AxesSubplot at 0x7f4ff6c17da0>
# 如果是想kedplot輸入的二維數據,則可以獲得二維數據的可視化 sns.kdeplot(data)
/sw/ana/lib/python3.7/site-packages/seaborn/distributions.py:679: UserWarning: Passing a 2D dataset for a bivariate plot is deprecated in favor of kdeplot(x, y), and it will cause an error in future versions. Please update your code.
warnings.warn(warn_msg, UserWarning) /sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<matplotlib.axes._subplots.AxesSubplot at 0x7f4ff6b99f28>
# jointplot可以同時看到兩個變量的聯合分布和單變量的獨立分布
with sns.axes_style('white'):
sns.jointplot('X', 'Y', data, kind='kde')
/sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
# 向jointplot函數傳遞一些參數,可以用六邊形塊代替頻次直方圖。
with sns.axes_style("white"):
sns.jointplot('X', 'Y', data, kind='hex')
/sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
ii. 矩陣圖
對多維數據集進行可視化時,需要用到矩陣圖(pair plot)來表示變量中任意兩個變量的關系,探索多 維數據不同維度的相關性。
iris = sns.load_dataset('iris')
iris.head()
.dataframe tbody tr th { vertical-align: top;
}
.dataframe thead th { text-align: right;
}
sepal_length
- 0 5.1
- 1 4.9
- 2 4.7
- 3 4.6
- 4 5.0
sepal_width petal_length petal_width
3.5 1.4 0.2
3.0 1.4 0.2
3.2 1.3 0.2
3.1 1.5 0.2
3.6 1.4 0.2
species
setosa
setosa
setosa
setosa
setosa
#展示四個變量的矩陣
sns.pairplot(iris, hue='species', size=2.5)
/sw/ana/lib/python3.7/site-packages/seaborn/axisgrid.py:2065: UserWarning: The `size` parameter has been renamed to `height`; pleaes update your code.
warnings.warn(msg, UserWarning) /sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<seaborn.axisgrid.PairGrid at 0x7f4ff5f5b080>
iii. 分面頻次直方圖 借助數據子集的頻次直方圖觀察數據是一種很好的觀察方法,下面案例展示的是服務員收取消費的數據。
tips = sns.load_dataset('tips')
tips.head()
.dataframe tbody tr th { vertical-align: top;
}
.dataframe thead th { text-align: right;
}
total_bill
- 0 16.99
- 1 10.34
- 2 21.01
- 3 23.68
- 4 24.59
tip
sex
smoker
day time
Sun Dinner
Sun Dinner
Sun Dinner
Sun Dinner
Sun Dinner
size
2
3
3
2
4
1.01
1.66
3.50
3.31
3.61
Female
Male
Male
Male
Female
No
No
No
No
No
tips['tip_pct'] = 100 * tips['tip'] / tips['total_bill']
grid = sns.FacetGrid(tips, row='sex', col='time', margin_titles=True)
grid.map(plt.hist, 'tip_pct', bins=np.linspace(0, 40, 15))
<seaborn.axisgrid.FacetGrid at 0x7f4ff5bccb38>
iv. 因子圖
因子圖(Factor Plot)也是對數據子集進行可視化的方法,可以用來觀察一個參數在另一個參數間隔中的分布情
況。
with sns.axes_style(style='ticks'):
g = sns.factorplot('day', 'total_bill', 'sex', data=tips, kind='box')
g.set_axis_labels("Day", 'Total_bill')
/sw/ana/lib/python3.7/site-packages/seaborn/categorical.py:3666: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
warnings.warn(msg)
v. 聯合分布圖 可以用jointplot畫出不同數據集的聯合分布和各數據樣本本身的分布。
#聯合分布圖
with sns.axes_style("white"):
sns.jointplot('total_bill', 'tip', data=tips, kind='hex')
/sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
#帶回歸擬合的聯合分布圖
#聯合分布圖自行進行kde和回歸
sns.jointplot('total_bill', 'tip', data=tips, kind='reg')
/sw/ana/lib/python3.7/site-packages/scipy/stats/stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
<seaborn.axisgrid.JointGrid at 0x7f4ff2f6d5f8>
vi. 條形圖
planets = sns.load_dataset('planets') planets.head()
.dataframe tbody tr th { vertical-align: top;
}
.dataframe thead th { text-align: right;
}
method
- 0 Radial Velocity 1
- 1 Radial Velocity 1
- 2 Radial Velocity 1
- 3 Radial Velocity 1
- 4 Radial Velocity 1
number
orbital_period mass distance year
269.300 7.10
874.774 2.21
763.000 2.60
326.030 19.40
516.220 10.50
77.40 2006
56.95 2008
19.84 2011
110.62 2007
119.47 2009
with sns.axes_style("white"):
g = sns.factorplot('year', data=planets, aspect=2, \
kind='count', color='steelblue')
g.set_xticklabels(step=5)
/sw/ana/lib/python3.7/site-packages/seaborn/categorical.py:3666: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
warnings.warn(msg)
#對比用不同的方法發現行星數量
with sns.axes_style("white"):
g = sns.factorplot('year', data=planets, aspect=4.0, \
kind='count', hue='method', order=range(2001, 2015))
g.set_ylabels('Number of Planets Discovered')
/sw/ana/lib/python3.7/site-packages/seaborn/categorical.py:3666: UserWarning: The `factorplot` function has been renamed to `catplot`. The original name will be removed in a future release. Please update your code. Note that the default `kind` in `factorplot` (`'point'`) has changed `'strip'` in `catplot`.
warnings.warn(msg)