Chapter 9 matplotlib
This section is to give a brief introduction to matplotlib module. The task is to equip us with a tool to monitor bivariate relationship.
First,
All of plotting functions expect
np.array or
np.ma.masked_array
as input.
主要透過matplotlib底下的pyplot module來完成
9.1 module: pyplot
- tutorial: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
9.1.1 Figure and subplots

figure(圖)
subplot(子圖)
Axes: 所有子圖以格子形式(grids)在圖面figure的配置。
一個figure至少包含一個subplot.
9.1.2 作圖1: methods on subplot objects
把每個subplot當成物件,而以「作圖只是作用在該物件的method」概念來完成圖形。
結果是一個tuple: (element1, element2)
element1: figure基本資訊。
element2: array. 代表Axes,其每個元素是一張子圖的資訊。
element1 and element2均為object,各有可用來修改圖形設計的method.
x=md.x
# 對每個subplot使用.plot method
ax[0,0].plot(x, x, label='linear')
ax[0,1].plot(x, x**2, label='quadratic')
ax[1,0].plot(x, x**3, label='cubic')
ax[1,1].plot(x, x**4, label='power 4')
plt.show()練習創一個有1 x 3 subplots的figure,並在三個subplot各自畫上一個圖形。
9.1.3 作圖2: functions on current subplot
第二種方法不是subplot的method而是使用繪圖“函數”在“current subplot”作圖。
- 創好current figure後一次指定一個current subplot,即
plt.figure()後接著plt.subplot()來定義current subplot.
x = md.x
plt.figure() # 創一個current figure
plt.subplot(221) # 由current figure的 2 x 2 subplots裡,指定第1個subplot為current subplot- 使用
plt.<作圖函數>完成current subplot之後;以下使用plt.plot()函數:
- move on到新的current subplot,再使用
plt.<作圖函數>繪圖;以此類推,一個個subplot完成。
## current subplot改為222
plt.subplot(222)
plt.plot(x, x**2, label='quadratic')
## current subplot改為223
plt.subplot(223)
plt.plot(x, x**3, label='cubic')
## current subplot改為224
plt.subplot(224)
plt.plot(x, x**4, label='power 4')
plt.show()查詢current figure and axes:
當你有許多figure且不時要來回修改各別的subplots,使用作圖1 Object Oriented Programming(OOP)方法會比較好,因為每個subplot都有各自名稱比較不會搞混
9.1.4 用plt.plot()來繪製不同圖形
plt.plot(x,y)內定為line plot, 但它可用來畫各種線圖、點圖及線+點圖。可使用:
plt.plot(x,y,fmt)`
來變更設定。
fmt: “<marke><linestyle><color>”
markers
| character | |
|---|---|
| . | point |
| , | pixel |
| o | circle |
| v | triangle_down |
| ^ | triangle_up |
| < | triangle_left |
| > | triangle_right |
| 1 | tri_down |
| 2 | tri_up |
| 3 | tri_left |
| 4 | tri_right |
| s | square |
| p | pentagon |
| * | star |
| h | hexagon1 |
| H | hexagon2 |
| + | plus |
| x | x |
| D | diamond |
| d | thin_diamond |
| | | vline |
| _ | hline |
linestyles
| character | description |
|---|---|
| - | solid line style |
| – | dashed line style |
| -. | dash-dot line style |
| : | dotted line style |
colors
| character | color |
|---|---|
| b | blue |
| g | green |
| r | red |
| c | cyan |
| m | magenta |
| y | yellow |
| k | black |
| w | white |