__getitem__ method not defined on Axes

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")
axs[2].set_ylabel("Temperature", color="tab:red")

"__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 Axes.

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 [19]: fig, ax = plt.subplots(squeeze=False)

In [20]: ax
Out[20]: array([[<AxesSubplot:>]], dtype=object)

In [21]: type(ax)
Out[21]: numpy.ndarray

In [22]: ax.shape
Out[22]: (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.

a somewhat related issue I have is when calling imshow on an axis.

ax[0].imshow(example)

gives

imshow: Unknown
Cannot access member "imshow" for type "list[Axes]"
  Member "imshow" is unknownPylancereportGeneralTypeIssues

As noted above, the stubs are not currently provided by Matplotlib. However, there is now active work to include them in the library so in future we should have more control over this sort of problem.