You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 4.1.7:网格子图
## plt.subplot()绘制子图
若干彼此对齐的行列子图是常见的可视化任务,`matplotlib`拥有一些可以轻松创建它们的简便方法。最底层且最常用的方法是`plt.subplot()`。这个函数在一个网格中创建一个子图该函数由三个整型参数依次为将要创建的网格子图行数、列数和索引值索引值从1开始从左上到右下递增。
```python
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')
```
![](22.jpg)
## 调整子图之间的间隔
如上图`y`轴的刻度有的已经和前面的子图重叠,`matplotlib`提供`plt.subplots_adjust`命令调整子图之间的间隔。用面向对象接口的命令` fig.add_subplot() `可以取得同样的效果。
```python
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 7):
ax = fig.add_subplot(2, 3, i)
ax.text(0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')
```
![](23.jpg)
这里我们通过设置` plt.subplots_adjust`的` hspace `与 `wspace`参数设置与图形高度与宽度一致的子图间距,数值以子图的尺寸为单位。
## plt.subplots创建网格
当我们需要创建一个大型网格子图时,就没办法使用前面那种亦步亦趋的方法了,尤其是当你想隐藏内部子图的`x`轴与`y`轴标题时。`matplotlib`提供了`plt.subplots()`来解决这个问题。这个函数不是用来创建单个子图的,而是用一行代码创建多个子图,并放回一个包含子图的`numpy`数组。关键参数是行数与列数以及可选参数`sharex`与`sharey`。
让我们创建一个` 2 × 3 `的网格子图,同行使用相同的`y`坐标,同列使用相同的`y`轴坐标:
```python
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
```
![](24.jpg)
设置`sharex`与`sharey`参数后,我们就可以自动去掉网格内部子图的标签。
坐标轴实例网格的放回结果是一个`numpy`数组,这样就可以通过标准的数组取值方式轻松获取想要的坐标轴了:
```python
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')
```
![](25.jpg)