Given a gridspec object in matplotlib, I want to automatically iterate through all its indices so I can add the corresponding Axes automatically, something like:
for i, j in gspec.indices: # whatever those indices are
axs[i,j] = fig.add_subplot(gspec[i][j])
How do I do that, without knowing how many rows or columns the gridspec has in advance?
gspec.get_geometry()returns the number of rows and of columns. Here is some example code:If
axsisn't needed as numpy array, the conversion to numpy array can be left out.Note that the code assumes you need a subplot in every possible grid position, which also can be obtained via
fig, axs = plt.subplots(...). Agridspecis typically used when you want to combine grid positions to create custom layouts, as shown in the examples of the tutorial.