Have pyplot.subplots return an np array no matter how many plots are created

Hello!

I was wondering if it would be preferable to have pyplot.subplots always return a numpy array of axes. For example as it is now doing something like this:

fig, axes = plt.subplots(len(listofPlotData), 1)

Will result in “axes” being a numpy array or a SubplotAxes object depending on what the length of listofPlotData ends up being. However, since that number isn’t known ahead of time you need to follow that with something like this:

if (len(listofPlotData) > 1):
    axes = axes.ravel()
else:
    axes = [axes]

If you want to do something like index into it in a loop. All in all, as it’s currently implemented it doesn’t feel very pythonic, especially since subplots will usually result in more than one axes (at least it seems like it would considering you might not use subplots if you’re only plotting one set of axes). I don’t think that we should have to treat the return value differently for different cases. If it’s always a list, I can use one simple line of code to handle the output.

Unless I’m not using this function as intended, if so please let me know so I can clean up my code.

[edited by tacaswell to add formatting]

Author: Fantashit

1 thought on “Have pyplot.subplots return an np array no matter how many plots are created

  1. @migz, I think that if you use

    fig, axes = plt.subplots(len(listofPlotData), 1, squeeze=False)

    you will get the desired behavior.

Comments are closed.