为什么许多示例在Matplotlib/pyplot/python中使用`fig,ax = plt.subplots()` [英] Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

查看:111
本文介绍了为什么许多示例在Matplotlib/pyplot/python中使用`fig,ax = plt.subplots()`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • Modify tick label text
  • http://matplotlib.org/examples/pylab_examples/boxplot_demo2.html

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

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')

推荐答案

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

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()

比这更简洁:

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

这篇关于为什么许多示例在Matplotlib/pyplot/python中使用`fig,ax = plt.subplots()`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆