Matplotlib Tutorial: Python Plotting
Matplotlib速查表
seaborn: 統(tǒng)計(jì)數(shù)據(jù)可視化. Seaborn 一個(gè)基于Matplotlib的Python可視化庫(kù)。為畫(huà)出美觀(guān)的統(tǒng)計(jì)圖表而提供高階API悬秉。
工作流
Matplotlib畫(huà)圖澄步,可視化數(shù)據(jù),分為六步:
- 準(zhǔn)備數(shù)據(jù)
- 創(chuàng)建畫(huà)板(Figure和泌、Axes)
- 畫(huà)plot
- 調(diào)整
- 保存savefig
- 展示show
注意:上面步驟是按順序執(zhí)行的村缸,莫顛倒。
下面代碼段給出了一個(gè)完整的流程:
import matplotlib.pyplot as plt
import numpy as np
# step 1
x = np.linspace(start=0, stop=np.pi, num=100)
y = np.sin(x)
# step 2
fig = plt.figure()
ax = fig.add_subplot(111)
# step 3 & 4
ax.plot(x, y,
color='lightblue',
linewidth=3)
ax.scatter([x[20], x[49], x[79]], [y[20], y[49], y[79]],
color='darkblue',
marker='^')
# step 4
ax.set_xlim(0, np.pi)
# step 5
plt.savefig('foo.png', transparent=True)
# step 6
plt.show()
plt.cla() # clean axis
plt.clf() # clean figure
plt.close() # close window
上面代碼畫(huà)出的圖如下所示:
Figure和Axes
上面的圖示除了正常的內(nèi)容之外武氓,額外添加了Matplotlib里面的畫(huà)圖需要理解的基本元素梯皿,即Figure和Axes∠厮。可以把Figure對(duì)象想象成一個(gè)大的畫(huà)板东羹,若要作畫(huà),還必須依賴(lài)坐標(biāo)系A(chǔ)xes忠烛。一個(gè)Figure對(duì)象可以持有多個(gè)子圖属提,但每個(gè)子圖都需要獨(dú)立的坐標(biāo)系。所以步驟二創(chuàng)建畫(huà)板
美尸,實(shí)際是在創(chuàng)建Figure對(duì)象冤议,添加一個(gè)(或多個(gè))坐標(biāo)系(子圖)。記住师坎,這里子圖
和坐標(biāo)系
是同樣的概念恕酸。
在Matplotlib中創(chuàng)建子圖的方式不止一種,我這里只向大家介紹一種以免混淆屹耐。
如下代碼使用fig.add_subplot()
方法創(chuàng)建了4個(gè)子圖在同一個(gè)Figure上尸疆。
fig = plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None)
ax1 = fig.add_subplot(221) # row-column-num
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
然后你就可以分別在不同的子圖上展示數(shù)據(jù)了。如果是fig.add_subplot(111)
惶岭,那就只返回一個(gè)子圖(坐標(biāo)系)寿弱,就像第一個(gè)代碼段那樣。
上面的代碼看起來(lái)略顯繁瑣按灶,如果你想一次創(chuàng)建一個(gè)2行2列個(gè)子圖在一個(gè)figure上症革,那么只需要一行代碼就可以了:
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
# fig, axes = plt.subplots(nrows=2, ncols=2)
# ax1, ax2, ax3, ax4 = axes[0,0], axes[0,1], axes[1,0], axes[1,1]
上面兩種創(chuàng)建多個(gè)子圖的方法分別使用了Figure對(duì)象的add_subplot()
方法和plt的subplots()
方法。
-
Figure.add_subplot()
方法每次添加一個(gè)子圖鸯旁,返回這個(gè)子圖的坐標(biāo)系噪矛。 -
plt.subplots()
方法一次性創(chuàng)建并返回全部坐標(biāo)系量蕊。 - 如果你習(xí)慣直接調(diào)用plt,并且一次只創(chuàng)建一個(gè)子圖艇挨,那么
plt.subplot(nrows, ncols, plot_number)
是不錯(cuò)的選擇残炮。
到此為止,給出的這些創(chuàng)建Axes的方法都涉及到subplot
缩滨,與之對(duì)應(yīng)的是另一種創(chuàng)建Axes的方式Figure.add_axes((left, bottom, width, height))
势就,這個(gè)方法創(chuàng)建一個(gè)矩形區(qū)域,(left, bottom)
是矩形左下角的坐標(biāo)脉漏,width
是矩形區(qū)域的寬度苞冯,height
是矩形區(qū)域的高度,然后返回這個(gè)區(qū)域的坐標(biāo)供畫(huà)圖使用侧巨。雖然都返回坐標(biāo)系舅锄,但這這兩種方式,subplot
和Figure.add_axes
司忱,返回的是兩種不同的坐標(biāo)系對(duì)象:
-
subplot
返回的是matplotlib.axes._subplots.AxesSubplot
皇忿,自帶網(wǎng)格框架 -
add_axes
返回的是matplotlib.axes._axes.Axes
,更自由
常用的數(shù)據(jù)圖
ax.plot()
matplotlib.axes.Axes.plotAxes.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, **kwargs)
s
是每個(gè)點(diǎn)的大小烘贴,當(dāng)每個(gè)點(diǎn)的大小有意義時(shí)禁添,特別有用,例如氣泡圖桨踪,每個(gè)氣泡面積代表大小老翘。
marker
默認(rèn)為'o'
。
alpha
為點(diǎn)的透明度锻离,0為透明铺峭,1為不透明。當(dāng)數(shù)據(jù)之間有遮擋汽纠,但又需要顯示出來(lái)時(shí)卫键,設(shè)置透明度,例如0.5虱朵,是個(gè)不錯(cuò)的選擇莉炉。
matplotlib.axes.Axes.scatterax.bar()
ax.barh()
ax.axhline()
ax.axvline()
ax.fill()
ax.fill_between()
ax.arrow()
ax.quiver()
ax.streamplot()
ax.hist()
ax.boxplot()
ax.violinplot()
ax.imshow(img, cmap='gist_earth', interpolation='nerarest', vmin=-2, vmax=2)
調(diào)整你的數(shù)據(jù)圖
除了基本的數(shù)據(jù)圖之外,大部分情況下都需要添加更多的信息對(duì)圖表進(jìn)行說(shuō)明碴犬,或者協(xié)調(diào)坐標(biāo)系等絮宁,使數(shù)據(jù)圖表更加美觀(guān)、一致服协,表達(dá)信息更加清晰易懂绍昂!
本節(jié)內(nèi)容參考Matplotlib官網(wǎng)
顏色color c
縮寫(xiě)和全稱(chēng)表示顏色:
‘b’ - blue
‘g’ - green
‘r’ - red
‘c’ - cyan
‘m’ - magenta
‘y’ - yellow
‘k’ - black
‘w’ - white
十六進(jìn)制字符串表示顏色:
#008000
RGB或者RGBA元組:
(0,1,0,1)
灰度階(字符串):
'0.8'
如果你有多種類(lèi)別的數(shù)據(jù),例如10種,每種類(lèi)別都需要唯一的顏色表示窘游,這在聚類(lèi)結(jié)果可視化中很常見(jiàn)唠椭。此時(shí),seaborn提供了簡(jiǎn)潔的方法創(chuàng)建類(lèi)別顏色sns.palplot(sns.color_palette("hls", 10))
忍饰,這個(gè)方法直接返回一個(gè)RGB顏色三元組序列贪嫂,可以直接在Matplotlib需要提供顏色的時(shí)候使用。你也許在使用之前需要先展示一下這些顏色喘批,調(diào)用sns.palplot(colors)
即可撩荣。例如
sns.palplot(sns.color_palette("hls", 8))
這個(gè)方法產(chǎn)生的顏色只改變顏色見(jiàn)的色調(diào)hue值铣揉,同時(shí)保持亮度饶深、對(duì)比度不變,所以人眼看起來(lái)會(huì)更加舒服逛拱。
標(biāo)記marker
字符 | 樣式 |
---|---|
'-' | solid line style |
'--' | dashed line style |
'-.' | dash-dot line style |
':' | dotted line style |
'.' | point marker |
',' | pixel marker |
'o' | circle marker |
'v' | triangle_down marker |
'^' | triangle_up marker |
'<' | triangle_left 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 |