Matplotlib Tutorial: Python Plotting
Matplotlib速查表
seaborn: 統(tǒng)計數據可視化. Seaborn 一個基于Matplotlib的Python可視化庫。為畫出美觀的統(tǒng)計圖表而提供高階API。
工作流
Matplotlib畫圖,可視化數據,分為六步:
- 準備數據
- 創(chuàng)建畫板(Figure、Axes)
- 畫plot
- 調整
- 保存savefig
- 展示show
注意:上面步驟是按順序執(zhí)行的,莫顛倒。
下面代碼段給出了一個完整的流程:
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
上面代碼畫出的圖如下所示:

Figure和Axes
上面的圖示除了正常的內容之外,額外添加了Matplotlib里面的畫圖需要理解的基本元素,即Figure和Axes。可以把Figure對象想象成一個大的畫板,若要作畫,還必須依賴坐標系Axes。一個Figure對象可以持有多個子圖,但每個子圖都需要獨立的坐標系。所以步驟二創(chuàng)建畫板,實際是在創(chuàng)建Figure對象,添加一個(或多個)坐標系(子圖)。記住,這里子圖和坐標系是同樣的概念。
在Matplotlib中創(chuàng)建子圖的方式不止一種,我這里只向大家介紹一種以免混淆。
如下代碼使用fig.add_subplot()方法創(chuàng)建了4個子圖在同一個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)
然后你就可以分別在不同的子圖上展示數據了。如果是fig.add_subplot(111),那就只返回一個子圖(坐標系),就像第一個代碼段那樣。
上面的代碼看起來略顯繁瑣,如果你想一次創(chuàng)建一個2行2列個子圖在一個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)建多個子圖的方法分別使用了Figure對象的add_subplot()方法和plt的subplots()方法。
-
Figure.add_subplot()方法每次添加一個子圖,返回這個子圖的坐標系。 -
plt.subplots()方法一次性創(chuàng)建并返回全部坐標系。 - 如果你習慣直接調用plt,并且一次只創(chuàng)建一個子圖,那么
plt.subplot(nrows, ncols, plot_number)是不錯的選擇。
到此為止,給出的這些創(chuàng)建Axes的方法都涉及到subplot,與之對應的是另一種創(chuàng)建Axes的方式Figure.add_axes((left, bottom, width, height)),這個方法創(chuàng)建一個矩形區(qū)域,(left, bottom)是矩形左下角的坐標,width是矩形區(qū)域的寬度,height是矩形區(qū)域的高度,然后返回這個區(qū)域的坐標供畫圖使用。雖然都返回坐標系,但這這兩種方式,subplot和Figure.add_axes,返回的是兩種不同的坐標系對象:
-
subplot返回的是matplotlib.axes._subplots.AxesSubplot,自帶網格框架 -
add_axes返回的是matplotlib.axes._axes.Axes,更自由
常用的數據圖
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是每個點的大小,當每個點的大小有意義時,特別有用,例如氣泡圖,每個氣泡面積代表大小。
marker默認為'o'。
alpha為點的透明度,0為透明,1為不透明。當數據之間有遮擋,但又需要顯示出來時,設置透明度,例如0.5,是個不錯的選擇。
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)
調整你的數據圖
除了基本的數據圖之外,大部分情況下都需要添加更多的信息對圖表進行說明,或者協(xié)調坐標系等,使數據圖表更加美觀、一致,表達信息更加清晰易懂!
本節(jié)內容參考Matplotlib官網
顏色color c
縮寫和全稱表示顏色:
‘b’ - blue
‘g’ - green
‘r’ - red
‘c’ - cyan
‘m’ - magenta
‘y’ - yellow
‘k’ - black
‘w’ - white
十六進制字符串表示顏色:
#008000
RGB或者RGBA元組:
(0,1,0,1)
灰度階(字符串):
'0.8'
如果你有多種類別的數據,例如10種,每種類別都需要唯一的顏色表示,這在聚類結果可視化中很常見。此時,seaborn提供了簡潔的方法創(chuàng)建類別顏色sns.palplot(sns.color_palette("hls", 10)),這個方法直接返回一個RGB顏色三元組序列,可以直接在Matplotlib需要提供顏色的時候使用。你也許在使用之前需要先展示一下這些顏色,調用sns.palplot(colors)即可。例如
sns.palplot(sns.color_palette("hls", 8))

這個方法產生的顏色只改變顏色見的色調hue值,同時保持亮度、對比度不變,所以人眼看起來會更加舒服。
標記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 |