首页 > 解决方案 > Matplotlib 外轴破坏子图布局

问题描述

我想绘制一个带有 3 个子图的图形。中间的有 3 个不同的 x 轴,其中一个被分离并放置在子图下方。当我Gridspec用于布局时,绘图区域等距分布,但不同子图的轴标签之间的填充有很大不同:

这是重现该图的代码:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(3.375, 6.5))
gs0 = gridspec.GridSpec(3, 1, figure=fig)

ax0 = fig.add_subplot(gs0[0])
ax0.set_xlabel('x label 0')

ax1 = fig.add_subplot(gs0[1])
ax1.set_xlabel('x label 1a')
secax1 = ax1.twiny()
secax1.xaxis.set_ticks_position('bottom')
secax1.xaxis.set_label_position('bottom')
secax1.spines['bottom'].set_position(('outward', 40))
secax1.set_xlabel('x label 1b')
thax1 = ax1.twiny()
thax1.set_xlabel('x label 1c')

ax2 = fig.add_subplot(gs0[2])
ax2.set_xlabel('x label 2a')
ax2.set_ylabel('y label 2')
secax2 = ax2.twiny()
secax2.set_xlabel('x label 2b')

plt.tight_layout()
plt.savefig('3 subplots same size.png', dpi=300)
plt.show()

我正在寻找一种方法来使完整子图之间的间距相等,以及附加轴及其标签等所有内容。或者一种在网格内手动移动子图的方法。子图不需要保持相同的大小。

我试着改变height_ratiosas

gs0 = gridspec.GridSpec(3, 1, figure=fig, height_ratios=[1, 1.5, 1])

但它不会影响地块之间的空间。

标签: pythonmatplotlibsubplotmultiple-axes

解决方案


您可以使用 plt.subplots 并在真实图之间放置不可见的“间隙图”,然后您可以通过更改间隙图的 height_ratio 来调整间隙

f, (ax0, gap1, ax1, gap2, ax2) = plt.subplots(5, 1,figsize=(3.375,8), gridspec_kw={'height_ratios': [1,1,1,1.75,1]})


gap1.axis('off')# Make the gap plots invisable
gap2.axis('off')# Make the gap plots invisable

#ax0 = fig.add_subplot(gs0[0])
ax0.set_xlabel('x label 0')

#ax1 = fig.add_subplot(gs0[2])
ax1.set_xlabel('x label 1a')
secax1 = ax1.twiny()
secax1.xaxis.set_ticks_position('bottom')
secax1.xaxis.set_label_position('bottom')
secax1.spines['bottom'].set_position(('outward', 40))
secax1.set_xlabel('x label 1b')
thax1 = ax1.twiny()
thax1.set_xlabel('x label 1c')

#ax2 = fig.add_subplot(gs0[5])
ax2.set_xlabel('x label 2a')
ax2.set_ylabel('y label 2')
secax2 = ax2.twiny()
secax2.set_xlabel('x label 2b')

输出

在此处输入图像描述


推荐阅读