Python matplotlib 中 plt.figure() 的必要性是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38666527/
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 21:17:02  来源:igfitidea点击:

What is the necessity of plt.figure() in matplotlib?

pythonmatplotlib

提问by Mainul Islam

plt.figure(figsize=(10,8))

plt.scatter(df['attacker_size'][df['year'] == 298],
        # attacker size in year 298 as the y axis
        df['defender_size'][df['year'] == 298],
        # the marker as
        marker='x',
        # the color
        color='b',
        # the alpha
        alpha=0.7,
        # with size
        s = 124,
        # labelled this
        label='Year 298')

In the above snippet of code collected from Scatterplot in Matplotlib, what is the necessity of plt.figure()?

在上面从Matplotlib 中的 Scatterplot收集的代码片段中,有什么必要plt.figure()

采纳答案by Mainul Islam

The purpose of using plt.figure()is to create a figure object.

使用的目的plt.figure()是创建一个图形对象。

The whole figure is regarded as the figure object. It is necessary to explicitly use plt.figure()when we want to tweak the size of the figure and when we want to add multiple Axes objects in a single figure.

整个图形被视为图形对象。plt.figure()当我们想要调整图形的大小以及当我们想要在单个图形中添加多个 Axes 对象时,有必要显式使用。

# in order to modify the size
fig = plt.figure(figsize=(12,8))
# adding multiple Axes objects  
fig, ax_lst = plt.subplots(2, 2)  # a figure with a 2x2 grid of Axes

Parts of a Figure

图的组成部分

回答by Suever

It is not always necessary because a figureis implicitly created when you create a scatterplot; however, in the case you have shown, the figure is being created explicitly using plt.figureso that the figure will be a specific size rather than the default size.

它并不总是必要的,因为 afigure是在您创建scatter绘图时隐式创建的;但是,在您显示的情况下,图形是显式创建的plt.figure,因此图形将是特定大小而不是默认大小。

The other option would be to use gcfto get the current figure after creating the scatterplot and set the figure size retrospectively:

另一种选择是gcf在创建scatter绘图后使用获取当前图形并追溯设置图形大小:

# Create scatter plot here
plt.gcf().set_size_inches(10, 8)