matplotlib 的 subplots() 中的 [1] 是什么意思?

What's the meaning of [1] in matplotlib's subplots()?

前段时间看到matplotlib的subplots()用法是这样的:

fig, ax1 = plt.subplots()[1]

我出于某种原因在我自己的脚本中使用了它,但不幸的是我完全忘记了其中 [1] 的含义(我应该在我的代码中添加注释!)。有人能告诉我它的作用吗?

我将尝试解释 [1] 是什么,以及为什么它可能不是您真正想要得到的 step-by-step。此外,我假设您没有按字面意思 运行 fig, ax = plt.subplots()[1],因为这应该会出错,因为此对象的第二个元素中没有要解压的内容。我将使用 4 个子图 (2,2) 的示例。

所以,首先,plt.figure()returns一个tuple,一个figure和一个Axes的集合(取决于多少行和你作为参数传递的列)。所以:

a = plt.subplots(2,2)  # 2,2 is an example, it could also be empty, so same as (1,1); the below would still hold
type(a)
len(a)

this returns tuple of len = 2。如果你现在检查元组的第一个元素是什么,你会看到它是实际的空数字(图形描述):

a[0]

虽然第二个元素是 Axes (an Axes 的数组,但它是包含数据 space 的图像区域,或者我喜欢如何思考它“集合的实际表示给定图形上的数据”)。

a[1]

array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7fe02397c650>,
    <matplotlib.axes._subplots.AxesSubplot object at 0x7fe022c1e4d0>],
   [<matplotlib.axes._subplots.AxesSubplot object at 0x7fe022deb210>,
    <matplotlib.axes._subplots.AxesSubplot object at 0x7fe0239b5ed0>]],
  dtype=object)

现在,如果您明确将选择限制在 plt.subplots() 元组的第二个元素,这意味着您只是抓取 Axes 以解压缩到 figax

fig, ax = a[1]
fig

这个returns:

array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fe02397c650>,
   <matplotlib.axes._subplots.AxesSubplot object at 0x7fe022c1e4d0>],
  dtype=object)

ax

这个returns:

array([<matplotlib.axes._subplots.AxesSubplot object at 0x7fe022deb210>,
   <matplotlib.axes._subplots.AxesSubplot object at 0x7fe0239b5ed0>],
  dtype=object)

所以基本上您将第一行的 Axes 分配给了 fig 对象,将第二行的 Axes 分配给了 ax 对象。根据您接下来的绘图功能如何进行,这些子图可能从未被使用过,或者您以某种方式没有收到错误,因为您选择了特定的子图大小。当然,如果你的目标是实际只使用 plt.subplots() 的第二个元素,即 Axes 的集合,你可以这样做。但是 fig 实际上将不再是一个数字。只是为了演示当我像您建议的那样使用整个绘图管道时会发生什么(例如使用 iris 数据集):

fig, ax = plt.subplots(2,2)[1]
ax[0].scatter(x=iris.sepal_length, y=iris.sepal_width) # Filling in the first `Axes`
ax[1].scatter(x=iris.sepal_width, y=iris.sepal_length) # Filling in the second `Axes`
plt.show()

最后,如果您想阅读更多相关信息,subplots() 上的 matplotlib documentation 有更多示例,并且还显示 plt.subplots(),无论你传递给它的形状,总是 returns fig, ax 的元组(其中“ax:axes.Axes 对象或 Axes 对象数组”)。