1

Within a loop, I need to be able to produce figures with both 2 * 1 or 2 * n subplots. below the code I am using which throw an error when the list of commodities has length = 1.

chart_types=["actual", "forecast"]
for country, commodities, element in [["United States of America", ["Avocado", "Mango", "Pineapple"], "Import"],
                                      ["Costa Rica", ["Pineapple"], "Export"],
                           ]:
    commodities_num=len(commodities)
    fig, ax = plt.subplots(commodities_num, chart_type_num, figsize=(8*chart_type_num,4*commodities_num), tight_layout=True)

    fig.suptitle(country+": "+element, fontsize=16, y=.99)

    for i, commodity in enumerate(commodities):
        for h, chart_type in enumerate(chart_types):
            ax[i,h].set_title(commodity + " " + chart_type)

Is there a way to avoid the "IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed" error?

1 Answers1

1

Set squeeze=False in your call to subplots() to have it always return a 2D array.

See https://matplotlib.org/3.5.1/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib-pyplot-subplots

Jeff
  • 1,234
  • 8
  • 16