matplotlib系列(2)-- 多子图绘制功能

在matplotlib下,一个画布(Figure)对象可以包含多个子图(Axes),可以使用subplot()快速绘制。

1、subplot介绍

1
subplot(numRows, numCols, plotNum)

图表的整个绘图区域被分成numRows行和numCols列,plotNum参数指定创建的Axes对象所在的区域。

2、subplot应用举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import matplotlib.pyplot as plt
import numpy as np

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

t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)

fig = plt.figure(figsize=(16, 10), dpi= 80) # 画布

ax1 = plt.subplot(221) # 两行两列中的第一行第一列位置
ax1.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

ax2 = plt.subplot(222) # 两行两列中的第一行第二列位置
ax2.plot(t2, np.cos(2 * np.pi * t2), 'r--')

ax3 = plt.subplot(212) # 两行一列中的第二行的位置
ax3.plot([1, 2, 3, 4], [1, 4, 9, 16])

plt.show()