Using gs = gridspec.GridSpec(3, 3)
, you have created essentially a 3 by 3 "grid" for your plots. From there, you can use gs[...,...]
to specify the location and size of each subplot, by the number of rows and columns each subplot fills in that 3x3 grid. Looking in more detail:
gs[1, :-1]
specifies where on the gridspace your subplot will be. For instance ax2 = plt.subplot(gs[1, :-1])
says: put the axis called ax2
on the first row (denoted by [1,...
) (remember that in python, there is zero indexing, so this essentially means "second row down from the top"), stretching from the 0th column up until the last column (denoted by ...,:-1]
). Because our gridspace is 3 columns wide, this means it will stretch 2 columns.
Perhaps it's better to show this by annotating each axis in your example:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :-1])
ax3 = plt.subplot(gs[1:, -1])
ax4 = plt.subplot(gs[-1, 0])
ax5 = plt.subplot(gs[-1, -2])
ax1.annotate('ax1, gs[0,:] \ni.e. row 0, all columns',xy=(0.5,0.5),color='blue', ha='center')
ax2.annotate('ax2, gs[1, :-1]\ni.e. row 1, all columns except last', xy=(0.5,0.5),color='red', ha='center')
ax3.annotate('ax3, gs[1:, -1]\ni.e. row 1 until last row,\n last column', xy=(0.5,0.5),color='green', ha='center')
ax4.annotate('ax4, gs[-1, 0]\ni.e. last row, \n0th column', xy=(0.5,0.5),color='purple', ha='center')
ax5.annotate('ax5, gs[-1, -2]\ni.e. last row, \n2nd to last column', xy=(0.5,0.5), ha='center')
plt.show()
