使用GridSpec制作多列/行子图布局

GridSpec是布置子打印网格的一种灵活方式。下面是一个使用3x3网格和横跨所有三列、两列和两行的轴的示例。

GridSpec示例

  1. import matplotlib.pyplot as plt
  2. from matplotlib.gridspec import GridSpec
  3. def format_axes(fig):
  4. for i, ax in enumerate(fig.axes):
  5. ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
  6. ax.tick_params(labelbottom=False, labelleft=False)
  7. fig = plt.figure(constrained_layout=True)
  8. gs = GridSpec(3, 3, figure=fig)
  9. ax1 = fig.add_subplot(gs[0, :])
  10. # identical to ax1 = plt.subplot(gs.new_subplotspec((0, 0), colspan=3))
  11. ax2 = fig.add_subplot(gs[1, :-1])
  12. ax3 = fig.add_subplot(gs[1:, -1])
  13. ax4 = fig.add_subplot(gs[-1, 0])
  14. ax5 = fig.add_subplot(gs[-1, -2])
  15. fig.suptitle("GridSpec")
  16. format_axes(fig)
  17. plt.show()

下载这个示例