3

I am plotting columns of a pandas dataframe in subplots. Which columns to plot is stored in an array, an. The below code works fine if len(an)>1, i.e. if I plot more than one graph,

    fig, axs = plt.subplots(len(an))
    for index, item in enumerate(an, start=0):
        gd.plot(ax=axs[index],x="Date",y=item)

but it fails with the error

TypeError: 'AxesSubplot' object is not subscriptable

if len(an)==1.

Is it possible to make subplots work, if there is just a single plot to plot, or do I have to treat this case separately with an if?

user1583209
  • 1,637
  • 3
  • 24
  • 42
  • Does this answer your question? [Matplotlib: TypeError: 'AxesSubplot' object is not subscriptable](https://stackoverflow.com/questions/52273546/matplotlib-typeerror-axessubplot-object-is-not-subscriptable) – kiranpradeep Nov 14 '20 at 03:30

1 Answers1

7

According to matplotlib's documentation, the parameter "squeeze" solves your problem:

squeeze: bool, optional, default: True

  • If True, extra dimensions are squeezed out from the returned array of Axes:
    • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
    • for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.
    • for NxM, subplots with N>1 and M>1 are returned as a 2D array.
  • If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

So the solution to your problem would be:

fig, axs = plt.subplots(1,len(an),squeeze=False)
for index, item in enumerate(an, start=0):
    gd.plot(ax=axs[0,index],x="Date",y=item)
Kloster Matias
  • 423
  • 4
  • 9
  • 1
    Thanks. I swapped indices around to have vertically stacked plots but your solution works perfectly. So I have: `fig, axs = plt.subplots(len(an),1,squeeze=False)` and ` gd.plot(ax=axs[index,0],x="Date",y=item)` . – user1583209 May 16 '20 at 15:16
  • Your welcome @user1583209. As a friendly reminder. If my answer solved your problem, click the big checkbox to mark it as an accepted answer. Not only does it help me, but other users who may have a similar question in the future. – Kloster Matias May 16 '20 at 15:51