Skip to content

Why is numpy.ravel() required in this code that produces small multiples?

I found some code to generate a set of small multiples and it is working perfectly.

fig, axes = plt.subplots(6,3, figsize=(21,21))
fig.subplots_adjust(hspace=.3, wspace=.175)
for ax, data in zip(axes.ravel(), clean_sets):
    ax.plot(data.ETo, "o")

The line for ax, data in zip(axes.ravel(), clean_sets): contians .ravel() but I do not understand what this is actually doing or why it is necessary.

If I take a look at the docs I find the following:

Return a contiguous flattened array.

A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.

I guess the return that corresponds to axes from plt.subplot() is a multidimensional array that can’t be iterated over, but really I’m not sure. A simple explanation would be greatly appreciated.

What is the purpose of using .ravel() in this case?



Your guess is correct. plt.subplots() returns either an Axes or a numpy array of several axes, depending on the input. In case a 2D grid is defined by the arguments nrows and ncols, the returned numpy array will be a 2D array as well.

This behaviour is explained in the pyplot.subplots documentation inside the squeeze argument,

squeeze : bool, optional, default: True
If True, extra dimensions are squeezed out from the returned Axes object:

  • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
  • for Nx1 or 1xN subplots, the returned object is a 1D numpy object array of Axes objects are returned as numpy 1D arrays.
  • for NxM, subplots with N>1 and M>1 are returned as a 2D arrays.

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 1×1.

Since here you have plt.subplots(6,3) and hence N>1, M>1, the resulting object is necessarily a 2D array, independent of what squeeze is set to.

This makes it necessary to flatten this array in order to be able to zip it. Options are

  • zip(axes.ravel())
  • zip(axes.flatten())
  • zip(axes.flat)