0

When we consider a call to plt.subplots() with a 2x2 grid:

def pltpoc():
  import matplotlib.pyplot as plt
  x = np.linspace(0,2*np.pi,10)
  y = np.sin(x)
  fig, axs = plt.subplots(2, 2)
  axs[0, 0].plot(x, y)
  axs[0, 0].set_title('Axis [0,0]')
  axs[0, 1].plot(x, y, 'tab:orange')
  axs[0, 1].set_title('Axis [0,1]')
  axs[1, 0].plot(x, -y, 'tab:green')
  axs[1, 0].set_title('Axis [1,0]')
  axs[1, 1].plot(x, -y, 'tab:red')
  axs[1, 1].set_title('Axis [1,1]')
  plt.show()

pltpoc()

Things look swell:

enter image description here

There seems to be a different behavior for the axes returned by plt.subplots() when the number of rows is only 1. Consider this updated code with the only difference that it has one row not two:

def pltpoc1():
  import matplotlib.pyplot as plt
  x = np.linspace(0,2*np.pi,10)
  y = np.sin(x)
  fig, axs = plt.subplots(1, 2)
  axs[0, 0].plot(x, y)
  axs[0, 0].set_title('Axis [0,0]')
  axs[0, 1].plot(x, y, 'tab:orange')
  axs[0, 1].set_title('Axis [0,1]')
  plt.show()

pltpoc1()

Now we have a completely different behavior:

Traceback (most recent call last):   File "/usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3296, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)   File "<ipython-input-3-434adc6ec1d8>", line 1, in <module>
    pltpoc1()   File "<ipython-input-2-3b01fe0b14d2>", line 6, in pltpoc1
    axs[0, 0].plot(x, y) IndexError: too many indices for array

So .. why is one row "special" ?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • @ImportanceOfBeingErnest I'd argue my question is more concise and clear on this specific issue of squeeze / one row. – WestCoastProjects Jun 18 '19 at 20:44
  • From the other question your answer is spot-on about _squeeze_ : no debate on the value of your answer. – WestCoastProjects Jun 18 '19 at 20:52
  • Your question is indeed (IMHO) a little bit different than the one pointed, but you'll find the answer inside. You have to set the parameter `squeeze`to `False`, `squeeze=False`. – FiReTiTi Sep 23 '21 at 22:14

0 Answers0