# Matplotlib 中如何创建不同大小的子图 subplot

Jinku Hu 2023年1月30日 2020年3月28日 Matplotlib Matplotlib Subplot

## `gridspec` 方法

``````import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure()
spec = gridspec.GridSpec(ncols=2, nrows=1,
width_ratios=[2, 1])

ax0.plot(range(5), range(5, 10))
ax1.plot(range(5), range(5, 10))

plt.show()
``````

``````spec = gridspec.GridSpec(ncols=2, nrows=1,
width_ratios=[2, 1])
``````

``````ax0 = fig.add_subplot(spec[0])
``````

## `gridspec_kw` 方法

``````import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2,
gridspec_kw={
'width_ratios': [2, 1],
'height_ratios': [1, 2]})

ax[0][0].plot(range(5), range(5, 10))
ax[0][1].plot(range(5), range(10, 5, -1))
ax[1][0].plot(range(5), range(5, 10))
ax[1][1].plot(range(5), range(10, 5, -1))

plt.show()
``````

`gridspec_kw` 是具有 `GridSpec` 构造函数关键字的字典，用于指定子图的网格。

## `subplot2grid` 方法

`subplot2grid` 允许子图在网格索引中占用多个单元格。

``````def subplot2grid(shape,
loc,
rowspan=1,
colspan=1,
fig=None,
**kwargs):
``````

`shape` 是网格的形状，具有 2 个整数的序列，其第一个元素是行数，第二个元素是列数。

`loc``axis` 放置在网格中的位置。它也是 2 个整数的序列，其第一个元素是行号，第二个元素是列号。

`rowspan``colspan``axis` 向右（`rowspan`）或向底部（`colspan`）跨越的行数或列数。

``````import matplotlib.pyplot as plt

fig = plt.figure()

ax0 = plt.subplot2grid((1, 5), (0, 0), colspan=3)
ax1 = plt.subplot2grid((1, 5), (0, 3), colspan=2)

ax0.plot(range(5), range(5, 10))
ax1.plot(range(5), range(10, 5, -1))

plt.show()
``````

``````ax0 = plt.subplot2grid((1, 5), (0, 0), colspan=3)
ax1 = plt.subplot2grid((1, 5), (0, 3), colspan=2)
``````

`ax0` 位于 `(0, 0)` 单元格中，占据 3 列，而 `ax1` 位于 `(0, 3)` 中，并且占据其他两列。

Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.