1. 程式人生 > >matplotlib.pyplot 導引

matplotlib.pyplot 導引

pre war 區域 lib imp nump 三維 .text tps

matplotlib.pyplot 是采用 python 語言和使用數值數學庫 numpy 數組數據的繪圖庫.其主要目標是用於數據的可視化顯示.

輸出圖形組成

matplotlib.pyplot 模塊中,其繪制的輸出圖形 (Figure) 的各組成部分,如下圖所示

技術分享圖片

其中

  Figure 是整個輸出圖形,記錄了所有子 Axes 對象,一些特殊的 artists (如標題,圖例等) 和畫布 (canvas).畫布 (canvas) 對用戶是不可見的.

  Axes 是含有數據空間的圖像區域.一個 figure 可以包含多個 Axes,但一個給定的 Axes 只能在一個 Figure 中.註意 Axes 與 Axis 的區別,Axis是指數學上的坐標軸,Axes可以包含 2 個 (二維) 或 3 個坐標軸 (三維).在 matplotlib 模塊中,matplotlib.axes.Axes類,包含大多數的圖形元素,如坐標軸 (matplotlib.axis.Axis), 刻度 (matplotlib.axis.Tick), 二維線段 (matplotlib.lines.Line2D), 文本 (matplotlib.text.Text), 多邊形 (matplotlib.patches.Polygon),並設置坐標系統;matplotlib.pyplot.axes(arg=None, **kwargs) 函數向當前的圖形 (current figure) 中,增加一個 Axes 對象,並設置其為當前的 Axes 對象;matplotlib.pyplot.axis(*v, **kwargs) 函數用於獲取或設置坐標軸屬性.

  在 Figure 上的任何對象,基本都是 Artist.當渲染圖形時,所有的 Artists 都會畫到畫布 (canvas) 上.大多數 Artists 都綁定到一個 Axes 上,不能被多個 Axes 共享,或從一個 Axes 移動到另一個.

編碼風格

  使用 matplotlib.pyplot 模塊,通常有兩種編碼風格,一種是采用面向對象接口 (object-oriented interface) 的編碼風格,另一種是類似 MATLAB (MATLAB-like) 的編碼風格.對於復雜的圖形繪制,推薦采用面向對象接口的編碼風格.

  • 面向對象編碼風格的示例代碼,如下所示.
import
matplotlib.pyplot as plt import numpy as np x = np.arange(0, 10, 0.2) y = np.sin(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y) plt.show()

上述代碼中,使用 pyplot 創建和顯示圖形,剩下的使用對象方法實現,其中 ax 對象是 Axes 類的對象.對於 matplotlib.pyplot 模塊,Axes 類和它的成員函數使用面向對象接口的主要入口點.

  • 類似 MATLAB 的編碼風格的示例代碼,如下所示
import matplotlib.pyplot as plt
import numpy as np x = np.arange(0, 10, 0.2) y = np.sin(x) plt.figure() plt.subplot(111) plt.plot(x, y) plt.show()

pylab 和 pyplot 關系

matplotlib.pyplot 是 matplotlib 模塊中的一個模塊;pylab 是安裝 matplotlib 模塊時附帶安裝的模塊.

pylab 是一個帶來便利的模塊,其可以在單一的命名空間 (pylab namespace) 下導入用於繪圖的 matplotlib.pyplot 模塊和用於數值數學和操作數組的 numpy 模塊.雖然有許多例子使用 pylab,但不再推薦使用.其示例代碼,如下所示:

import pylab

x = pylab.arange(0, 10, 0.2)
y = pylab.sin(x)
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
pylab.show()

參考資料

1. Usage - The Matplotlib FAQ. https://matplotlib.org/faq/usage_faq.html.

2. matplotlib.pyplot - The Matplotlib API. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html.

3. pyplot summary - The Matplotlib API. https://matplotlib.org/api/pyplot_summary.html.

4. Axes class - The Matplotlib API. https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes

5. matplotlib.pyplot.axes - matplotlib.pyplot. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.axes.html#matplotlib.pyplot.axes

6. matplotlib.pyplot.axis - matplotlib.pyplot. https://matplotlib.org/api/_as_gen/matplotlib.pyplot.axis.html#matplotlib.pyplot.axis

7. Pyplot tutorials - Tutorials. https://matplotlib.org/tutorials/introductory/pyplot.html.

matplotlib.pyplot 導引