# 如何在 Matplotlib 中改变子图的大小和间距

Suraj Joshi 2023年1月30日

## `tight_layout()` 方法更改 Matplotlib 子图大小和间距

`tight_layout()` 方法会自动保持子图之间的正确间距。

``````import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 1 / (1 + np.exp(-x))
y4 = np.exp(x)

fig, ax = plt.subplots(2, 2)

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x, y4)

ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")

fig.tight_layout()
plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 1 / (1 + np.exp(-x))
y4 = np.exp(x)

fig, ax = plt.subplots(2, 2)

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x, y4)

ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")

plt.show()
``````

## `plt.subplots_adjust()` 方法更改 Matplotlib 子图间距

``````import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 1 / (1 + np.exp(-x))
y4 = np.exp(x)

fig, ax = plt.subplots(2, 2)

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x, y4)

ax[0, 0].set_title("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")

plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=0.35)

plt.show()
``````

``````plt.subplots_adjust(left=0.125, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=0.35)
``````

`wspace``hspace` 指定子图之间保留的空间。它们分别是轴的宽度和高度的分数。

`left``right``top``bottom` 参数指定了子图的四个边的位置。它们是图形的宽度和高度的比例。

## `plt.subplot_tool()` 方法更改 Matplotlib 子图大小和间距

``````import numpy as np
import matplotlib.pyplot as plt

im1 = np.random.random((50, 50))
im2 = np.random.random((40, 50))
im3 = np.random.random((50, 40))
im4 = np.random.random((60, 50))

plt.subplot(221)
plt.imshow(im1)
plt.subplot(222)
plt.imshow(im2)
plt.subplot(223)
plt.imshow(im3)
plt.subplot(224)
plt.imshow(im4)

plt.subplot_tool()
plt.show()
``````

## 在子图中激活 `constrained_layout=True`

`constrained_layout` 会自动调整子图和装饰，使其尽可能地适合图中。

``````import numpy as np
import matplotlib.pyplot as plt

a = np.linspace(0, 5, 100)

figure, axes = plt.subplots(2, 2, constrained_layout=True)

axes[0, 0].plot(x, np.exp(a))
axes[0, 1].plot(a, np.sin(a))
axes[1, 0].plot(a, np.cos(a))
axes[1, 1].plot(range(10))

axes[0, 0].set_title("subplot 1")
axes[0, 1].set_title("subplot 2")
axes[1, 0].set_title("subplot 3")
axes[1, 1].set_title("subplot 4")

plt.show()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.