1

I am having problems setting up a 2 column x 1 row subplot configuration in Python. If I go to 2 x 2 everything works fine, but 2 x 1 seems to drop the row dimension

Simplified code as follows, where I want to make 2 plots (numplots) with two columns (nx)

import matplotlib
import matplotlib.pyplot as plt 

numplots = 2
nx = 2
ny = int(numplots/2)
if ny != numplots/2:
  ny += 1
fig, ax = plt.subplots(nrows=ny, ncols=nx )  
print(ax.shape, nx, ny)  

The result of this code is the following;

(2,) 2 1

As you can see, ax has an empty second dimension - Why?

If I change numplots to 3 or greater, the shape of ax is fine

Mark Burgoyne
  • 1,524
  • 4
  • 18
  • 31
  • See [this post](https://stackoverflow.com/a/44604834/12046409) about the `squeeze` parameter to `plt.subplots` – JohanC Apr 13 '20 at 00:16

1 Answers1

2

Matplotlib uses numpy in its implementations. Numpy treats arrays of shape (n, 1) as simple vectors, thus (n,) means a vector. It should not have any influence on outcome of your plotting code.

Artur Kasza
  • 356
  • 1
  • 9
  • Thanks - the problem comes when I try to access the array with a 2D method later on. I guess I need to trap vector outcomes and treat them differently – Mark Burgoyne Apr 12 '20 at 23:39
  • 1
    Note that [`plt.subplots`](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplots.html) has a parameter `squeeze=True` which can be set to `False` to always get a 2D array of axes. With `squeeze=True` a 1x1 array gets squeezed to just a scalar. – JohanC Apr 12 '20 at 23:57