Attempting to access Axes items produces Pylance error complaining about getitem method not defined, but the code seems to work correctly. Here’s a snippet:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(4, 1, sharex="all")
"__getitem__" method not defined on type "Axes"
Apologies if I’m missing something stupid here but I’m a relative newcomer to pyplot/matplotlib
The result of
plt.subplots is either an
Axes or a NumPy array of
Axes. The type definitions are incorrectly stating it is just
We do not maintain the type definitions though, so you will have to report that to Pylance (or maybe Pyright; I’m not sure where the type definitions come from).
Thanks for the explanation. At runtime axs is an array which is why my code works ok. So nothing to worry about, just annoying.
If you always want a numpy array back you can do
In : fig, ax = plt.subplots(squeeze=False)
In : ax
Out: array([[<AxesSubplot:>]], dtype=object)
In : type(ax)
In : ax.shape
Out: (1, 1)
which will ensure you are always returned a 2D numpy array of
Axes objects. The default is to “do what I mean” and squeeze out any singleton dimensions.