Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib with a single subplot

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?

like image 512
user1583209 Avatar asked Aug 31 '25 02:08

user1583209


1 Answers

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)
like image 165
Kloster Matias Avatar answered Sep 02 '25 16:09

Kloster Matias