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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34162443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:33:00  来源:igfitidea点击:

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

pythonmatplotlibplotvisualization

提问by neelshiv

I'm learning to use matplotlibby studying examples, and a lot of examples seem to include a line like the following before creating a single plot...

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

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 = subplotswhen creating a single chart, and it only ever references ax after that. This is the code they use.

我看到这个函数被大量使用,即使这个例子只是试图创建一个图表。有什么其他好处吗?在创建单个图表时subplots()也使用了官方演示f, ax = subplots,并且在此之后它只引用 ax。这是他们使用的代码。

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

采纳答案by jonchar

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 figand ax. Having figis 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:

plt.subplots()是一个函数,它返回一个包含图形和轴对象的元组。因此,在使用时,fig, ax = plt.subplots()您可以将此元组解包到变量figax. fig如果您想更改图形级别的属性或稍后将图形保存为图像文件(例如,使用fig.savefig('yourfilename.png')),那么拥有会很有用。您当然不必使用返回的图形对象,但很多人稍后会使用它,因此很常见。此外,所有轴对象(具有绘图方法的对象)无论如何都有一个父图形对象,因此:

fig, ax = plt.subplots()

is more concise than this:

比这更简洁:

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

回答by Duskash

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.

正如文档中提到的,我们可以fig = plt.subplots(nrows=2, ncols=2)在一个图形对象中使用 grid(2,2) 设置一组子图。

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.

然后我们知道,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)

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.

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

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:

当然,如果使用参数为(nrows=1,ncols=4),那么格式应该是:

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.

希望这对你有帮助。

回答by Light_B

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.

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

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.

可以使用plt.subplots()一次制作所有子图,并将子图的图形和轴(轴的复数)作为元组返回。图形可以理解为画布的画布。

# 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.

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)

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

但是,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)

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

共享轴而使用plt.subplot(),则必须为每个轴单独指定,这可能会变得很麻烦。

回答by John T

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.AxesSubplotwhich you can't unpack.

除了上面的答案之外,您还可以检查使用type(plt.subplots())which 返回元组的对象类型,另一方面,type(plt.subplot())返回matplotlib.axes._subplots.AxesSubplot您无法解包的返回。