matplotlib绘制多个子图——subplot

在matplotlib下,一个Figure对象能够包含多个子图(Axes),可使用subplot()快速绘制,其调用形式以下:python

subplot(numRows, numCols, plotNum)

图表的整个绘图区域被分红numRows行和numCols列,plotNum参数指定建立的Axes对象所在的区域,如何理解呢?spa

若是numRows = 3,numCols = 2,那整个绘制图表样式为3X2的图片区域,用坐标表示为(1,1),(1,2),(1,3),(2,1),(2,2),(2,3)。这时,当plotNum = 1时,表示的坐标为(1,3),即第一行第一列的子图;code

import numpy as np
import matplotlib.pyplot as plt
# 分红2x2,占用第一个,即第一行第一列的子图
plt.subplot(221)
# 分红2x2,占用第二个,即第一行第二列的子图
plt.subplot(222)
# 分红2x1,占用第二个,即第二行
plt.subplot(212)
plt.show()


import matplotlib.pyplot as plt
import numpy as np


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

# t = np.arange(0., 5., 0.2)
# plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^')


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)

plt.figure(12)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

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

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

plt.show()