matplotlib子图的怪异之处

Weirdness of matplotlib subplot

我正在按照 this 教程水平制作两个子图。根据示例,以下内容应该有效。

import matplotlib.pylab as plt
import numpy

# Sample data
x = numpy.linspace(0, 2 * numpy.pi, 400)
y1 = numpy.sin(x ** 2)
y2 = numpy.cos(x ** 2)

figure, axes = plt.subplots(1, 2)
axes[0, 0].plot(x, y)
axes[0, 1].plot(x, y)

不幸的是,我收到以下错误消息。

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-124cb6e8d977> in <module>
      8 
      9 figure, axes = plt.subplots(1, 2)
---> 10 axes[0, 0].plot(x, y)
     11 axes[0, 1].plot(x, y)

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

此外,如果我 运行 axes.shape,我得到的输出是 (2,)。我希望它是 (1, 2)。我错过了什么?

[请注意,前面的示例是一个最低限度的工作示例,在我的代码中作为特例出现。我不想通过前面示例中的 (ax1, ax2) 路线,因为我不知道我提前想要多少个子图,所以我必须以编程方式执行此操作。

特别是,我有 $ n $ 个特征,我想要形状为 $ (ceil(n / 2), 2) $ 的子图。所以我会使用 axes[i // 2, i % 2] ,其中 i 是我的迭代变量。但是当 $n = 2$ 时,我的代码就崩溃了。]

提前致谢!

[编辑:添加了上下文以回答 Tim 的评论。]

根据 matplotlib documentation 对于 plt.subplots:

  • 如果只构建了一个子图 (nrows=ncols=1),则生成的单个 Axes 对象将return编辑为标量。
  • 对于 Nx1 或 1xM 子图,returned 对象是 Axes 对象的一维 numpy 对象数组。
  • 对于 NxM,N>1 和 M>1 的子图被return编辑为二维数组。

这是默认行为,可以通过将 squeeze 参数设置为 False(在您的情况下为 plt.subplots(1, 2, squeeze = False))来更改它,在这种情况下它将始终 return 二维数组:

the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.