问题:为什么很多示例在Matplotlib / pyplot / python中使用`fig,ax = plt.subplots()`

我正在matplotlib通过学习示例来学习使用方法,在创建单个图之前,很多示例似乎包含如下一行:

fig, ax = plt.subplots()

这里有些例子…

我看到此功能使用了很多,即使该示例仅尝试创建单个图表。还有其他优势吗?官方演示subplots()还在f, ax = subplots创建单个图表时使用,并且此后仅引用ax。这是他们使用的代码。

# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

I’m learning to use matplotlib by studying examples, and a lot of examples seem to include a line like the following before creating a single plot…

fig, ax = plt.subplots()

Here are some examples…

I see this function used a lot, even though the example is only attempting to create a single chart. Is there some other advantage? The official demo for subplots() also uses f, ax = subplots when creating a single chart, and it only ever references ax after that. This is the code they use.

# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

回答 0

plt.subplots()是一个返回包含图形和轴对象的元组的函数。因此,在使用时fig, ax = plt.subplots(),将此元组解压缩到变量fig和中axfig如果您要更改图形级属性或以后将图形另存为图像文件(例如,使用fig.savefig('yourfilename.png')),则具有很有用。您当然不必使用返回的图形对象,但是许多人以后会使用它,因此很常见。另外,所有轴对象(具有绘图方法的对象)总有一个父图形对象,因此:

fig, ax = plt.subplots()

比这更简洁:

fig = plt.figure()
ax = fig.add_subplot(111)

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don’t have to use the returned figure object but many people do use it later so it’s common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:

fig, ax = plt.subplots()

is more concise than this:

fig = plt.figure()
ax = fig.add_subplot(111)

回答 1

这里只是一个补充。

下面的问题是,如果要在图中添加更多子图该怎么办?

如文档中所述,我们可以用来fig = plt.subplots(nrows=2, ncols=2)在一个图形对象中设置带有grid(2,2)的一组子图。

然后我们知道,fig, ax = plt.subplots()返回一个元组,让我们fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)首先尝试。

ValueError: not enough values to unpack (expected 4, got 2)

它引发了一个错误,但是不用担心,因为我们现在看到plt.subplots()实际上返回了一个包含两个元素的元组。第一个必须是图形对象,另一个必须是一组子图对象。

因此,让我们再试一次:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

并检查类型:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

当然,如果将参数用作(nrows = 1,ncols = 4),则格式应为:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

因此,只需记住将列表的构造与我们在图中设置的子图网格相同即可。

希望这对您有帮助。

Just a supplement here.

The following question is that what if I want more subplots in the figure?

As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2) to set a group of subplots with grid(2,2) in one figure object.

Then as we know, the fig, ax = plt.subplots() returns a tuple, let’s try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) firstly.

ValueError: not enough values to unpack (expected 4, got 2)

It raises a error, but no worry, because we now see that plt.subplots() actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.

So let’s try this again:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

and check the type:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.

Hope this would be helpful for you.


回答 2

作为补充的问题和答案,上面也有一个重要区别plt.subplots()plt.subplot(),通知失踪's'底。

可以plt.subplots()一次制作所有子图,然后将子图的图形和轴(复数轴)返回为元组。可以将图形理解为在其中绘制草图的画布。

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

plt.subplot()如果要单独添加子图,则可以使用。它仅返回一个子图的轴。

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

但是,plt.subplots()它是首选,因为它为您提供了更轻松的选项来直接自定义您的整个身材

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

共享轴 但是,使用时plt.subplot(),必须为每个轴分别指定,这可能会很麻烦。

As a supplement to the question and above answers there is also an important difference between plt.subplots() and plt.subplot(), notice the missing 's' at the end.

One can use plt.subplots() to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

Whereas, you can use plt.subplot() if you want to add the subplots separately. It returns only the axis of one subplot.

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

However, plt.subplots() is preferred because it gives you easier options to directly customize your whole figure

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

Shared axes whereas, with plt.subplot(), one will have to specify individually for each axis which can become cumbersome.


回答 3

除了上述问题的答案,你可以检查使用对象的类型type(plt.subplots()),它返回一个元组,而另一方面,type(plt.subplot())回报matplotlib.axes._subplots.AxesSubplot您无法解压缩。

In addition to the answers above, you can check the type of object using type(plt.subplots()) which returns a tuple, on the other hand, type(plt.subplot()) returns matplotlib.axes._subplots.AxesSubplot which you can’t unpack.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。