试图在特定的subplot2grid之间添加空间,而不是全部

时间:2018-01-24 09:41:11

标签: python matplotlib

以下创建了10个子图:

ax1 = plt.subplot2grid((4, 8), (0, 0), colspan=4, rowspan=2)
ax2 = plt.subplot2grid((4, 8), (0, 4), colspan=2, rowspan=1)
ax3 = plt.subplot2grid((4, 8), (0, 6), colspan=2, rowspan=1)
ax4 = plt.subplot2grid((4, 8), (1, 4), colspan=2, rowspan=1)
ax9 = plt.subplot2grid((4, 8), (1, 6), colspan=2, rowspan=1)

ax5 = plt.subplot2grid((4, 8), (2, 0), colspan=4, rowspan=2)
ax6 = plt.subplot2grid((4, 8), (2, 4), colspan=2, rowspan=1)
ax7 = plt.subplot2grid((4, 8), (2, 6), colspan=2, rowspan=1)
ax8 = plt.subplot2grid((4, 8), (3, 4), colspan=2, rowspan=1)
ax10 = plt.subplot2grid((4, 8),(3, 6), colspan=2, rowspan=1)

enter image description here

我想在顶部子图集和底部子图集之间添加一行空格。我尝试按如下方式添加一行(之前对我有用但现在不是出于某种原因),并将底部的所有子图向下移动一行:

ax1 = plt.subplot2grid((5, 8), (0, 0), colspan=4, rowspan=2)
ax2 = plt.subplot2grid((5, 8), (0, 4), colspan=2, rowspan=1)
ax3 = plt.subplot2grid((5, 8), (0, 6), colspan=2, rowspan=1)
ax4 = plt.subplot2grid((5, 8), (1, 4), colspan=2, rowspan=1)
ax9 = plt.subplot2grid((5, 8), (1, 6), colspan=2, rowspan=1)

ax5 = plt.subplot2grid((5, 8), (3, 0), colspan=4, rowspan=2)
ax6 = plt.subplot2grid((5, 8), (3, 4), colspan=2, rowspan=1)
ax7 = plt.subplot2grid((5, 8), (3, 6), colspan=2, rowspan=1)
ax8 = plt.subplot2grid((5, 8), (4, 4), colspan=2, rowspan=1)
ax10 = plt.subplot2grid((5, 8),(4, 6), colspan=2, rowspan=1)

然而,它为我生成了两个空的子图,我没有请求它们之间的那个空行(给我总共12个子图)。我只想要两组之间的空行或间距。

enter image description here

1 个答案:

答案 0 :(得分:1)

以下是使用gridspec获取所需内容的方法:

from matplotlib import pyplot as plt
from matplotlib import gridspec

gs = gridspec.GridSpec(5,8)

fig = plt.figure()
ax1 = fig.add_subplot(gs[0:2,0:4])
ax2 = fig.add_subplot(gs[0:1,4:6])
ax3 = fig.add_subplot(gs[0:1,6:8])
ax4 = fig.add_subplot(gs[1:2,4:6])
ax5 = fig.add_subplot(gs[1:2,6:8])


ax6 = fig.add_subplot(gs[3:5,0:4])
ax7 = fig.add_subplot(gs[3:4,4:6])
ax8 = fig.add_subplot(gs[3:4,6:8])
ax9 = fig.add_subplot(gs[4:5,4:6])
ax10 = fig.add_subplot(gs[4:5,6:8])

plt.show()

这给出了以下结果:

result of above code