首页 > 解决方案 > 调整单个子图间距

问题描述

fig = plt.figure(figsize=(14, 14))
ax0 = fig.add_subplot(12, 2, (1, 9))
ax1 = fig.add_subplot(12, 2, (2, 10))
ax2 = fig.add_subplot(14, 2, (13, 14))
ax3 = fig.add_subplot(14, 2, (15, 16))

for ax in (ax0, ax1, ax2, ax3):
    ax.set_xticks([])
    ax.set_yticks([])
fig.subplots_adjust(hspace=.25, wspace=.02)

产量

我可以ax2, ax3只减少底部两个子图 ( ) 之间的垂直间距吗?

标签: pythonmatplotlib

解决方案


这有点 hacky,但是您可以使用每个子图的边界框来将 ax3 的边界框移动到更靠近 ax2 的位置(此处触摸):

fig = plt.figure(figsize=(5, 5))        # Made smaller for the example
ax0 = fig.add_subplot(12, 2, (1, 9))
ax1 = fig.add_subplot(12, 2, (2, 10))
ax2 = fig.add_subplot(14, 2, (13, 14))
ax3 = fig.add_subplot(14, 2, (15, 16))

for ax in (ax0, ax1, ax2, ax3):
    ax.set_xticks([])
    ax.set_yticks([])

fig.subplots_adjust(hspace=.25, wspace=.02)

# Below is where the m"hack"gic happens
pos_ax3 = ax3.get_position()
pos_ax2 = ax2.get_position()
ywidth = pos_ax3.y1 - pos_ax3.y0

yspace = 0
pos_ax3.y0 = pos_ax2.y0 - ywidth * yspace
pos_ax3.y1 = pos_ax2.y0 - ywidth * (1 + yspace)
ax3.set_position(pos_ax3)

输出:

手动移动轴


推荐阅读