Python-Matplotlib-subplot()和subplots()之间的区别 [英] Python - matplotlib - differences between subplot() and subplots()

查看:1020
本文介绍了Python-Matplotlib-subplot()和subplots()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编码方面的新手,因此是python的新手,这听起来可能有些愚蠢,但是python中matplotlib的.subplot()和.subplots()方法之间的主要区别是什么?

I'm kind of new in coding and thus in python so this may sound quite dumb, but what are the main differences between .subplot() and .subplots() methods from matplotlib in python?

阅读 https://matplotlib.org/中的文档后,我在其他任何地方都找不到此解释.我推断出,使用这两种方法,您都可以创建任意数量的图形和绘图...因此对我来说,这两者似乎是完全一样的,它们只是处理图形,轴等的方式不同...还是我错了?

I didn't find this explanation anywhere else and after reading the documentation from https://matplotlib.org/ I inferred that with both methods you can create as many figures and plots as you want...so for me both of them seem to be quite the same thing and they just differ the way you can handle plots, axes, etc...or am I wrong?

顺便说一句,如果有任何区别,我正在jupyter笔记本中使用python3.

Btw, I am using python3 in jupyter notebook if it makes any difference.

推荐答案

来自matplotlib.pyplot.subplots()上的文档页面:

From the documentation page on matplotlib.pyplot.subplots():

此实用程序包装器使您可以在一次调用中方便地创建子图的通用布局,包括封闭的图形对象.

This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.

这意味着您可以使用此单个功能来创建一个只有几个代码行的带有多个子图的图形.例如,下面的代码将同时返回图形对象fig和轴对象的2x3数组axes,这使您可以轻松访问每个子图:

That means you can use this single function to create a figure with several subplots with only one line of code. For example, the code below will return both fig which is the figure object, and axes which is a 2x3 array of axes objects which allows you to easily access each subplot:

fig, axes = plt.subplots(nrows=2, ncols=3)

相反,matplotlib.pyplot.subplot()在指定的网格位置仅创建一个子图轴.这意味着将需要多行代码来达到与matplot.pyplot.subplots()在上述单行代码中所做的相同的结果:

In contrast, matplotlib.pyplot.subplot() creates only a single subplot axes at a specified grid position. This means it will require several lines of code to achieve the same result as matplot.pyplot.subplots() did in a single line of code above:

# first you have to make the figure
fig = plt.figure(1)

# now you have to create each subplot individually
ax1 = plt.subplot(231)
ax2 = plt.subplot(232)
ax3 = plt.subplot(233)
ax4 = plt.subplot(234)
ax5 = plt.subplot(235)
ax6 = plt.subplot(236)

上面的代码可以用循环压缩,但是使用起来仍然很繁琐.因此,我建议您使用matplotlib.pyplot.subplots(),因为它更简洁易用.

The code above can be condensed with a loop, but it is still considerably more tedious to use. I'd therefore recommend you use matplotlib.pyplot.subplots() since it is more concise and easy to use.

这篇关于Python-Matplotlib-subplot()和subplots()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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