【问题标题】:adjust matplotlib subplot axis + labels after applying tight_layout应用tight_layout后调整matplotlib子图轴+标签
【发布时间】:2020-08-14 08:44:21
【问题描述】:

我正在使用网格创建这个子图。代码和输出如下所示。当我尝试应用 plt.tight_layout() 函数来调整标签时,它不能正常工作。

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)
    ax.set_xlabel('Episode', fontsize=8)
    ax.set_ylabel('LPS',fontsize=8)
    ax.set_title("Learning Rate=0.9", fontsize=8)

fig = plt.figure()
ax1 = plt.subplot2grid((12, 8), (0, 0), colspan=4,rowspan=4)
ax2 = plt.subplot2grid((12, 8), (0, 4), colspan=4,rowspan=4)
ax3 = plt.subplot2grid((12, 8), (4, 1),rowspan=2,colspan=2)
ax4 = plt.subplot2grid((12, 8), (4, 5),rowspan=2,colspan=2)
ax5 = plt.subplot2grid((12, 8), (6, 2), colspan=4,rowspan=4)
ax6 = plt.subplot2grid((12, 8), (10, 0), colspan=2,rowspan=2)
annotate_axes(fig)
plt.tight_layout()
plt.savefig("Plot.png")
plt.show()

【问题讨论】:

  • 例如,添加figsize=(16,9) 以禁用警告。似乎是因为没有余地来减少它。
  • 您也可以尝试constrained_layout 进行更复杂的布局,但使用gridspec 而不是subplot2grid

标签: matplotlib data-visualization subplot


【解决方案1】:
import matplotlib.pyplot as plt

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)
        ax.set_xlabel('Episode', fontsize=8)
        ax.set_ylabel('LPS',fontsize=8)
        ax.set_title("Learning Rate=0.9", fontsize=8)

fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(12, 8)
ax1 = fig.add_subplot(gs[0:4, 0:4])
ax2 = fig.add_subplot(gs[0:4, 4:8])
ax3 = fig.add_subplot(gs[4:6, 1:3])
ax4 = fig.add_subplot(gs[4:6, 5:7])
ax5 = fig.add_subplot(gs[6:10, 2:6])
ax6 = fig.add_subplot(gs[10:12, 0:2])
annotate_axes(fig)
plt.savefig("Plot.png")
plt.show()

【讨论】: