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()

一个 ndarray 对象 x 是从np.arange() 函数作为上的值x axis.上的相应值y axis存储在另一个ndarray 对象 y.这些值是使用绘制的plot()matplotlib 包的 pyplot 子模块的功能。

图形由show()函数表示。

上面的代码应该产生以下输出:

Matplotlib Demo

代替线性图,值可以通过将格式字符串添加到plot()功能。可以使用以下格式字符。

序号.字符和描述
1

'-'

实线样式

2

'--'

虚线样式

3

'-.'

点划线样式

4

':'

虚线样式

5

'.'

点标记

6

','

像素标记

7

'o'

圆形标记

8

'v'

三角形向下标记

9

'^'

Triangle_up 标记

10

'<'

Triangle_left 标记

11

'>'

Triangle_right 标记

12

'1'

Tri_down 标记

13

'2'

Tri_up 标记

14

'3'

Tri_left 标记

15

'4'

Tri_right 标记

16

's'

方形标记

17

'p'

五边形标记

18

'*'

星标

19

'h'

Hexagon1 标记

20

'H'

Hexagon2 标记

21

'+'

加号标记

22

'x'

X marker

23

'D'

菱形记号笔

24

'd'

Thin_diamond 标记

25

'|'

Vline 标记

26

'_'

线标记

还定义了以下颜色缩写。

字符颜色
'b'Blue
'g'Green
'r'Red
'c'Cyan
'm'Magenta
'y'Yellow
'k'Black
'w'White

要显示表示点的圆圈,而不是上面示例中的线,请使用“ob”作为 plot() 函数中的格式字符串。

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()函数来生成条形图。下面的例子产生了两组x和y数组的条形图。

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