Axes是个二元数组,但是如果只有一行或者一列,就是一元数组。

1
2
3
4
5
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
for i in range(2):
for j in range(3):
ax[i, j].text(0.5, 0.5, str((i, j)),
fontsize=18, ha='center')

比起 plt.subplot(), plt.subplots() 用的0开始的index,这更pythonic。

1
2
3
4
for i in range(1, 7):
plt.subplot(2, 3, i)
plt.text(0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')

当然,还有一种奇技淫巧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from itertools import product

# 造个三进制生成器
binary_values = ['0', '1', '2']
n = 2
binary_iter = product(binary_values, repeat=n)

fig, ax = plt.subplots(2, 3)
for i in range(5):
index = next(binary_iter)
m = int(index[0])
n = int(index[1])
ax[m, n].text(0.5, 0.5, str((i, j)),
fontsize=18, ha='center')