Home > Software engineering >  How to return Axes objects generated by gridspec as though they were generated by plt.subplots
How to return Axes objects generated by gridspec as though they were generated by plt.subplots

Time:10-07

I construct several Axes objects using gridspec. I want to create an object axs which is a compilation of these Axes objects, but which I can call as though axs were created using _, axs=plt.subplots(*args, **kwargs). I've tried making a manual list:

axs = [[ax1, ax2, ...], [ax3, ax4, ...]]

But this is a nested list and will have to be accessed using axs[m][n] rather than axs[m,n] like a subplots object would. What's the right approach?

CodePudding user response:

You could just create an array yourself, similar to the nested list:

axs = np.asarray([[ax1, ax2, ...], [ax3, ax4, ...]])

It's not completely clear to me how you create the axes. But when you have for example your gridspec object, calling the subplots method should give you a similar array compared to plt.subplots:

axs = gs.subplots()

It might also be worth looking at the relatively new plt.subplot_mosaic which allows you name the axes, basically storing them in a dict:
https://matplotlib.org/stable/tutorials/provisional/mosaic.html#

Both plt.subplots and plt.subplot_mosaic also directly support the width and height ratio keywords (previously via gridspec_kw), so for most cases you might be able to get what you want directly with plt.subplots.

  • Related