在创建 matplotlib 图时,第一行 fig,ax=plt.subplots() 的相关性是什么?

What is the relevance of the first line fig,ax=plt.subplots(), when creating a matplotlib plot?

我正在 python 课程中学习数据可视化以帮助完成我的实验报告,但我似乎无法理解此散点图创建示例中第二行的用途:

import matplotlib.pyplot as plt
fig,ax = plt.subplots()
ax.scatter([1,2,3,4,5],[1,2,3,4,5])
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()

谁能解释一下第一行在这里做什么。 我才开始使用 python,之前我还没有见过这种语法(fig,ax = plt.subplots())。我试图通过编写 x,y=1 来测试是否可以将 2 个变量分配给同一事物,但我最终得到了一个错误 "int object is not iterable"。

我不明白的另一件事是 fig 在代码主体的任何地方使用?我目前的理解是,顶行定义了 figax 是什么,我可以看到 ax 在代码主体中用于定义散点图,但是 [= =15=]用过?我试图删除它和 运行 代码,但出现此错误:

'tuple' object has no attribute 'scatter'

如果有人能解释一下上面的误解。

I tried to test if it was a way to assign 2 variables to the same thing by writing x,y=1, I ended up getting an error "int object is not iterable".

你几乎是对的。 语法同时分配多个变量,但你缺少的是 plt.subplots() returns a tuple - 两个值配对在一起。

如果你想更好地理解它,你可以运行:

a, b = (1, 4)

a,b = 1, 4

(就python而言是一样的,如果使用或返回多个值,它将packs/unpacks值赋给一个元组)

I tried to delete it and run the code, but I got this error:

'tuple' object has no attribute 'scatter'

这也与您出现此错误的原因有关。该图确实没有在您的代码片段中使用,但您需要它 python 来理解您想要使用元组的一部分而不是元组本身。 例如:a=(1,2) 将导致包含一个元组,但在 a, b = 1, 2 中,每个创建的变量将包含一个整数。

在你的例子中,轴对象有一个方法 scatter,元组对象没有,因此你的错误。

根据 official docssubplots 创建一个图形和一组子图。具体来说,

Returns:

fig : Figure

ax : axes.Axes object or array of Axes objects. ax can be either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

现在当你这样做时

fig, ax = plt.subplots()

图形object赋给变量fig,轴object赋给变量ax

然后 fig 将允许您访问 figure-level 上的属性,例如图形标题。 ax 将使您能够访问各个子图级别的属性,例如每个子图的图例、axis-labels、刻度。如果您有多个子图,它将作为轴数组 objects。