使用 matplotlib 在两个轴之间调整 space,同时在其他轴上保持不变

Adjust space between two axes while keeping it constant on other axes using matplotlib

出于某种原因,我找不到这方面的信息(我很确定它存在于某处),但在下面的通用示例中,我想减少 ax1 和 ax2 之间的 hspace,同时保持相同的 hspace在 ax2-ax3 和 ax3-ax4 之间。

我也非常感谢任何指向此类示例的链接!

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


def annotate_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure()

gs1 = GridSpec(6, 1, hspace=0.2)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])

ax3 = fig.add_subplot(gs1[2:4])
ax4 = fig.add_subplot(gs1[4:6])

annotate_axes(fig)
plt.show()

可能适合您需要的一种方法是创建一个子网格(在此示例中,将 hspace 设置为 0):

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


def annotate_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

fig = plt.figure()

gs1 = GridSpec(6, 1, hspace=0.2)

# subgrid for the first two slots
# in this example with no space
subg = gs1[0:2].subgridspec(2, 1, hspace = 0)

# note the ax1 and ax2 being created from the subgrid
ax1 = fig.add_subplot(subg[0])
ax2 = fig.add_subplot(subg[1])

ax3 = fig.add_subplot(gs1[2:4])
ax4 = fig.add_subplot(gs1[4:6])

annotate_axes(fig)
plt.show()