NumPy - Matplotlib



Matplotlib 是 Python 的一個繪相簿。它與 NumPy 一起使用,提供了一個有效的開源替代 MatLab 的環境。它也可以與 PyQt 和 wxPython 等圖形工具包一起使用。

Matplotlib 模組最初由 John D. Hunter 編寫。自 2012 年以來,Michael Droettboom 擔任主要開發者。目前,Matplotlib 1.5.1 版本是可用的穩定版本。該軟體包以二進位制分發版和原始碼形式在 www.matplotlib.org 上提供。

通常,透過新增以下語句將軟體包匯入 Python 指令碼:

from matplotlib import pyplot as plt

這裡pyplot() 是 matplotlib 庫中最重要的函式,用於繪製二維資料。以下指令碼繪製方程式 y = 2x + 5

示例

import numpy as np 
from matplotlib import pyplot as plt 

x = np.arange(1,11) 
y = 2 * x + 5 
plt.title("Matplotlib demo") 
plt.xlabel("x axis caption") 
plt.ylabel("y axis caption") 
plt.plot(x,y) 
plt.show()

np.arange() 函式建立一個 ndarray 物件 x 作為x 軸上的值。y 軸上的對應值儲存在另一個ndarray 物件 y 中。這些值使用 matplotlib 包的 pyplot 子模組的plot() 函式繪製。

圖形表示由show() 函式顯示。

以上程式碼應產生以下輸出:

Matplotlib Demo

除了線性圖,還可以透過向plot() 函式新增格式字串來離散地顯示值。可以使用以下格式字元。

序號 字元 & 說明
1

'-'

實線樣式

2

'--'

虛線樣式

3

'-.'

點劃線樣式

4

':'

點線樣式

5

'.'

點標記

6

','

畫素標記

7

'o'

圓圈標記

8

'v'

下三角標記

9

'^'

上三角標記

10

'<'

左三角標記

11

'>'

右三角標記

12

'1'

下三角標記

13

'2'

上三角標記

14

'3'

左三角標記

15

'4'

右三角標記

16

's'

正方形標記

17

'p'

五角星標記

18

'*'

星形標記

19

'h'

六角形1標記

20

'H'

六角形2標記

21

'+'

加號標記

22

'x'

X 標記

23

'D'

菱形標記

24

'd'

細菱形標記

25

'|'

垂直線標記

26

'_'

水平線標記

還定義了以下顏色縮寫。

字元 顏色
'b' 藍色
'g' 綠色
'r' 紅色
'c' 青色
'm' 品紅色
'y' 黃色
'k' 黑色
'w' 白色

要在上面的示例中顯示錶示點的圓圈而不是線,請在 plot() 函式中使用“ob”作為格式字串。

示例

import numpy as np 
from matplotlib import pyplot as plt 

x = np.arange(1,11) 
y = 2 * x + 5 
plt.title("Matplotlib demo") 
plt.xlabel("x axis caption") 
plt.ylabel("y axis caption") 
plt.plot(x,y,"ob") 
plt.show() 

以上程式碼應產生以下輸出:

Color Abbreviation

正弦波圖

以下指令碼使用 matplotlib 繪製正弦波圖

示例

import numpy as np 
import matplotlib.pyplot as plt  

# Compute the x and y coordinates for points on a sine curve 
x = np.arange(0, 3 * np.pi, 0.1) 
y = np.sin(x) 
plt.title("sine wave form") 

# Plot the points using matplotlib 
plt.plot(x, y) 
plt.show() 
Sine Wave

subplot()

subplot() 函式允許您在同一圖形中繪製不同的內容。在以下指令碼中,繪製了正弦餘弦值

示例

import numpy as np 
import matplotlib.pyplot as plt  
   
# Compute the x and y coordinates for points on sine and cosine curves 
x = np.arange(0, 3 * np.pi, 0.1) 
y_sin = np.sin(x) 
y_cos = np.cos(x)  
   
# Set up a subplot grid that has height 2 and width 1, 
# and set the first such subplot as active. 
plt.subplot(2, 1, 1)
   
# Make the first plot 
plt.plot(x, y_sin) 
plt.title('Sine')  
   
# Set the second subplot as active, and make the second plot. 
plt.subplot(2, 1, 2) 
plt.plot(x, y_cos) 
plt.title('Cosine')  
   
# Show the figure. 
plt.show()

以上程式碼應產生以下輸出:

Sub Plot

bar()

pyplot 子模組提供bar() 函式來生成條形圖。以下示例生成了兩組xy 陣列的條形圖。

示例

from matplotlib import pyplot as plt 
x = [5,8,10] 
y = [12,16,6]  

x2 = [6,9,11] 
y2 = [6,15,7] 
plt.bar(x, y, align = 'center') 
plt.bar(x2, y2, color = 'g', align = 'center') 
plt.title('Bar graph') 
plt.ylabel('Y axis') 
plt.xlabel('X axis')  

plt.show()

此程式碼應產生以下輸出:

Bar Graph
廣告