Matplotlib variable subplots dimension IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

Matplotlib variable subplots dimension IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

在一个循环中,我需要能够生成包含 2 * 1 或 2 * n 个子图的图形。在我使用的代码下方,当商品列表的长度 = 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)

有没有办法避免“IndexError:数组的索引太多:数组是一维的,但有 2 个索引”错误?

在对 subplots() 的调用中设置 squeeze=False 以使其始终 return 二维数组。

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