Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7.9k
Description
Problem
subplots()
defaults to auto-squeezing the returned Axes array (returning a single array when one is requested, returning a 1D array when a single row or single column is requested), likely for practicality, but this makes dynamic layouts pretty annoying: if you writeaxs = fig.subplots(m, n)
wherem
andn
are somehow dynamically computed (based on some dataset characteristics) and then later plan to useaxs[i, j]
, you basically have an IndexError waiting to happen unless you can be certain thatm
andn
are never 1. Of course one can remember to always writesubplots(..., squeeze=False)
, but that's a bit verbose.
Proposed Solution
My preferred solution would probably have been to make the defaultm
andn
not 1, but None, so that None means "1 in that direction, and squeeze that direction" whereas 1 just means 1 (without squeezing). This would have fixed most common cases, e.g. if you writesubplots()
you get a single axes,subplots(3)
orsubplots(nrows=3)
orsubplots(ncols=3)
you get a 1D array,subplots(m, n)
(wherem
andn
are dynamically computed variables) you always get a 2D array. I think in practice the main back-incompatibility of this proposal that occurs in real life issubplots(1, 3)
(single row, likely not so uncommon), which would typically have to be writtensubplots(None, 3)
orsubplots(ncols=3)
orfig, (axs,) = subplots(3)
(for the additional unpacking).
Assuming that this backcompat breakage is not acceptable (it likely is not), one alternative would be to change the signature ofsubplots()
to also support taking a single2-tuple as argument (rather thannrows
andncols
separately, and makesubplots((m, n))
never squeeze the input. (Likely we wouldn't bother supportingm
orn
being None, in that case.) Then it would be OK to retrain my muscle memory to just always add an extra pair of parentheses when callingsubplots
.