Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weirdness of matplotlib subplot

I am following this tutorial to make two subplots horizontally. According to the examples, the following should work.

import matplotlib.pylab as plt
import numpy

# Sample data
x = numpy.linspace(0, 2 * numpy.pi, 400)
y1 = numpy.sin(x ** 2)
y2 = numpy.cos(x ** 2)

figure, axes = plt.subplots(1, 2)
axes[0, 0].plot(x, y)
axes[0, 1].plot(x, y)

Unfortunately, I get the following error message.

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-124cb6e8d977> in <module>
      8 
      9 figure, axes = plt.subplots(1, 2)
---> 10 axes[0, 0].plot(x, y)
     11 axes[0, 1].plot(x, y)

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

In addition, if I run axes.shape, I get the output as (2,). I would expect it to be (1, 2). What am I missing?

[Note that the earlier is a minimum working example which comes up as a special case in my code. I do not want to go via the (ax1, ax2) route in an earlier example because I do not exactly know how many subplots I want ahead of time, so I have to do this programmatically.

In particular, I have $ n $ features, and I want to subplots of shape $ (ceil(n / 2), 2) $. So I would use axes[i // 2, i % 2] where i is my iterating variable. But when $ n = 2 $, my code breaks down.]

Thanks in advance!

[Edit: added the context to answer Tim's comment.]

like image 913
Sudip Sinha Avatar asked Nov 05 '25 16:11

Sudip Sinha


1 Answers

As per matplotlib documentation for plt.subplots:

  • 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.

This is the default behaviour, and it can be changed by setting squeeze argument to False (plt.subplots(1, 2, squeeze = False) in your case), in which case it will always return a 2D array:

the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

like image 59
dm2 Avatar answered Nov 07 '25 10:11

dm2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!