Python 繪圖包 Matplotlib Pyplot (教程)


Pyplot 接口簡介

Pyplot 入門

matplotlib.pyplot 是命令風格函數的集合,使 Matplotlib 像 MATLAB 一樣工作。每個 Pyplot 函數對圖形做一些修改,例如:創建一個圖形,在圖形中創建一個繪圖區域,在繪圖區域中回值一些線條,用標簽裝飾圖形等等。

 matplotlib.pyplot中,在函數調用之間保留了各種狀態,以便跟蹤當前圖形和繪圖區域等內容,繪圖函數指向當前 軸(Axes 對象)。

注意

Pyplot API 通常不如面向對象的 API 靈活。在這里看到的大多數函數調用也可以作為 Axes 對象的方法調用。建議瀏覽教程和實力來了解這是如何工作的。

 

用 Pyplot 生成可視化效果非常快速:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4])

plt.ylabel('some numbers')

plt.show()

 

可能知道為什么 X軸的范圍是 0-3,Y 軸的范圍是 1-4。如果向 plot() 命令提供單個列表或數組,Matplotlib 將假定是一個 Y 值序列,並自動生成 X 值。因為 Python 范圍以 0 開頭,所以默認的 X 向量與 Y 的長度相同,但是以 0 開頭。因此 X 數據是[0, 1, 2, 3]。

plt.plot
([1, 2, 3, 4], [1, 4, 9, 16])

 

設置圖的樣式

對於每一對 X,Y 參數,第三個參數都是可選的,它是指示繪圖的顏色和線條類型的格式字符串。格式字符串的字母和符號來自 MATLAB,可以將一個顏色字符串與一個行樣式字符串連接起來。默認的格式字符串是"b-",這是一個純藍色的線。例如:要用紅色源泉回值上面的圖,代碼如下:

plt.plot
([1, 2, 3, 4], [1, 4, 9, 16], 'ro') 
plt.axis
([0, 6, 0, 20]) 
plt.show
()

 

有關行樣式和格式化字符串的完整列表,參見 plot() 文檔。上面示例中的 axis() 命令接受一個 [ xmin,xmax,ymin,ymax ] 列表,並指定軸的視口。

所有序列都在內部轉換成 numpy 數組。下面是示例:

import numpy as np

 

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2) 

 

# red dashes, blue squares and green triangles
plt.plot
(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') 
plt.show
()

 

使用關鍵詞字符串繪圖

在某些情況下,數據的格式允許使用字符串訪問特定的變量。例如:使用 numpy.recarray

pandas.DataFrame

Matplotlib 允許使用 data 關鍵字參數提供這樣的對象。如果提供了,那么可以生成包含與這些變量對應字符串的繪圖。

data = {'a': np.arange(50), 
 'c': np.random.randint(0, 50, 50), 
 'd': np.random.randn(50)} 
data['b'] = data['a'] + 10 * np.random.randn(50) 
data['d'] = np.abs(data['d']) * 100

 

plt.scatter
('a', 'b', c='c', s='d', data=data) 
plt.xlabel
('entry a') 
plt.ylabel
('entry b') 
plt.show
()

 

用分類變量繪圖

還可以使用分類變量創建繪圖。Matplotlib 允許直接將分類變量傳遞給許多繪圖函數。例如:

names = ['group_a', 'group_b', 'group_c'] 
values = [1, 10, 100] 

 

plt.figure
(1, figsize=(9, 3)) 

 

plt.subplot
(131) 
plt.bar
(names, values) 
plt.subplot
(132) 
plt.scatter
(names, values) 
plt.subplot
(133) 
plt.plot
(names, values) 
plt.suptitle
('Categorical Plotting') 
plt.show
()

 

控制線屬性

線有許多可以設置的屬性: linewidth、 dash style、 antialiased 等; 請參見matplotlib.lines.Line2D。有幾種方法可以設置 line 屬性:

  • 使用關鍵字方向圖:
    plt.plot
    (x, y, linewidth=2.0)
  • 使用 Line2D 實力的 setter 方法。Plot 返回一個 Line2D 對象列表,例如:line1, line2 = plot(x1, y1, x2, y2)。在下面的代碼中,假設只有一行,所以返回的列表長度為 1。使用元組拆分行,以獲得該列表的第一個元素:
    line, = plt.plot(x, y, '-') 
    line.set_antialiased(False) # turn off antialising
  • 使用  setp() 命令。下面的示例使用 MATLAB-style 的命令來設置行列表的多個屬性。顯而易見 setp 可以處理對象表單或單個對象。可以使用 Python 關鍵字參數或 MATLAB-style 的字符串或鍵值對。
    lines = plt.plot(x1, y1, x2, y2) 
    # use keyword args
    plt.setp(lines, color='r', linewidth=2.0) 
    # or MATLAB style string value pairs
    plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

    詳細的 Line2D 屬性。

若要獲取可設置行屬性的列表,請使用一行或多行作為參數調用 setp() 函數:

In [69]: lines = plt.plot([1, 2, 3]) 

 

In [70]: plt.setp(lines) 
 alpha: float 
 animated: [True | False] 
 antialiased or aa: [True | False] 
 ...snip

 

生成多個圖和軸

MATLAB 和 pyplot,具有當前圖形和當前 Axes(軸對象)。所有繪圖命令都應用於當前 Axes。函數 gca() 返回當前 Axes( matplotlib.axes.Axes 實例),gca() 返回當前圖形(matplotlib.figure.Figure 實例)。下面是創建兩個圖的代碼:

def f(t): 
 return np.exp(-t) * np.cos(2*np.pi*t) 

 

t1 = np.arange(0.0, 5.0, 0.1) 
t2 = np.arange(0.0, 5.0, 0.02) 

 

plt.figure
(1) 
plt.subplot
(211) 
plt.plot
(t1, f(t1), 'bo', t2, f(t2), 'k') 

 

plt.subplot
(212) 
plt.plot
(t2, np.cos(2*np.pi*t2), 'r--') 
plt.show
()

 

 figure() 命令是可選的,因為圖1是默認創建的,就像如果不手動指定任何坐標軸,默認情況下會創建一個子圖2 一樣。subplot() 命令 numrows,numcols,plot_number,其中plot_number 范圍從1到numrows * numcols。如果numrows * numcols < 10,那么 subplot 命令逗號是可選的。所以subplot(211)和subplot(2, 1, 1)是一樣的。

可以創建任何數量的子圖和軸。如果想動手設置一個坐標軸,可以使用 axes() 命令,該命令允許將位置指定為 axes([左,底,寬,高]),其中所有值都是小數(0-1)坐標。有關手動設置軸的示例,請參見 Axes Demo;有關許多子圖示例,請參見 Basic Subplot Demo

import matplotlib.pyplot as plt
plt.figure
(1) # the first figure
plt.subplot
(211) # the first subplot in the first figure
plt.plot
([1, 2, 3]) 
plt.subplot
(212) # the second subplot in the first figure
plt.plot
([4, 5, 6]) 

 

 

plt.figure
(2) # a second figure
plt.plot
([4, 5, 6]) # creates a subplot(111) by default

 

plt.figure
(1) # figure 1 current; subplot(212) still current
plt.subplot
(211) # make subplot(211) in figure1 current
plt.title
('Easy as 1, 2, 3') # subplot 211 title

可以使用 clf() 清楚當前軸。這是一個面向對象 API 的有狀態包裝器,可以參見 Artist 教程。

如果制作大量圖形,那么需要需要注意的:一個圖形所需的內存在使用 close()顯示關閉之前是不被完全釋放的。刪除對圖形的所有引用,[並 、或] 關閉窗口是不夠的。因為 pyplot 內部引用指到 close() 結束 

 

操作文本

 text() 命令可用於在任何位置添加文本,而 xlabel()、ylabel() 和 title() 則用於指定位置添加文本,可參見 Text in Matplotlib Plots

mu, sigma = 100, 15

x = mu + sigma * np.random.randn(10000)

 

# the histogram of the data

n, bins, patches = plt.hist(x, 50, density=1, facecolor='g', alpha=0.75)

 

 

plt.xlabel('Smarts')

plt.ylabel('Probability')

plt.title('Histogram of IQ')

plt.text(60, .025, r'$\mu=100,\ \sigma=15$')

plt.axis([40, 160, 0, 0.03])

plt.grid(True)

plt.show()

 

所有 text() 命令都返回一個 matplotlib.text.Text 實例。也可以通過setp() 來自定義屬性:

t = plt.xlabel('my data', fontsize=14, color='red')

更多 Text 屬性和布局詳細

Matplotlib 接受任何文本表達式中的 TeX 方程式。例如:要在標題中寫入表達式 σi=15,可以寫 TeX 表達式,周圍用 $ 包圍:

plt.title(r'$\sigma_i=15$')

標題字符串前面的 r 非常重要——它表示該字符串是一個原始字符串,並且不將反斜杠視為 python 轉義。 Matplotlib 有一個內置的 TeX 表達式解析器和布局引擎,並有自己的數學字體,詳情參看。因此,您可以跨平台使用數學文本,而無需安裝 TeX。 對於安裝了 LaTeX 和 dvipng 的用戶,還可以使用 LaTeX 格式化文本,並將輸出直接合並到顯示圖形或保存的 postscript 中。請參見使用 LaTeX 的文本。

注解文本

text() 命令的使用將文本房子在軸線上的任意位置。文本的一個常見用途是對 plot 的某些特性進行注釋,而annotate() 方法提供了幫助器功能,使注釋變得簡單。在注釋中,有兩點需要考慮:用 XY 參數表示的注釋位置位置額和文本 xytext 的位置。這兩個參數都是 ( x, y ) 元組。

 

在這個基本示例中,xy (箭頭頂端) xytext 位置(文本位置)都在數據坐標中。還有許多其它的坐標系可供選擇,詳情參見文檔高級注釋。更多例子可參見

 

對數 和 其它非線性軸

matplotlib.pyplot 不僅支持線性軸刻度,還支持對數和對數尺度。如果數據跨越多個數量級,這是常用的。改變一個軸的尺寸很容易:

plt.xscale('log')

下面顯示了 y 軸具有相同數據和不同尺度的四個繪圖示例:

from matplotlib.ticker import NullFormatter # useful for `logit` scale

 

# Fixing random state for reproducibility
np.random.seed
(19680801) 

 

# make up some data in the interval ]0, 1[
y = np.random.normal(loc=0.5, scale=0.4, size=1000) 
y = y[(y > 0) & (y < 1)] 
y.sort() 
x = np.arange(len(y)) 

 

# plot with various axes scales
plt.figure
(1) 

 

# linear
plt.subplot
(221) 
plt.plot
(x, y) 
plt.yscale
('linear') 
plt.title
('linear') 
plt.grid
(True) 

 

 

# log
plt.subplot
(222) 
plt.plot
(x, y) 
plt.yscale
('log') 
plt.title
('log') 
plt.grid
(True) 

 

 

# symmetric log
plt.subplot
(223) 
plt.plot
(x, y - y.mean()) 
plt.yscale
('symlog', linthreshy=0.01) 
plt.title
('symlog') 
plt.grid
(True) 

 

# logit
plt.subplot
(224) 
plt.plot
(x, y) 
plt.yscale
('logit') 
plt.title
('logit') 
plt.grid
(True) 
# Format the minor tick labels of the y-axis into empty strings with
# `NullFormatter`, to avoid cumbering the axis with too many labels.
plt.gca
().yaxis.set_minor_formatter(NullFormatter()) 
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust
(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, 
 wspace=0.35) 

 

plt.show
()

 

也可以添加自己的縮放,詳細信息請參閱開發人員創建縮放和轉換的指南

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM