Python - matplotlib - subplot() 和 subplots() 之间的差异 [英] Python - matplotlib - differences between subplot() and subplots()

查看:29
本文介绍了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 notebook 中使用 python3.

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

推荐答案

1.matplotlib.pyplot.subplots()

来自 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)

2.matplotlib.pyplot.subplot()

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

2. matplotlib.pyplot.subplot()

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)

或者你也可以使用fig的内置方法:

or you can also use built-in method of fig:

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(234)
ax5 = fig.add_subplot(235)
ax6 = fig.add_subplot(236)

结论

上面的代码可以用一个循环来压缩,但使用起来仍然相当乏味.因此,我建议您使用 matplotlib.pyplot.subplots(),因为它更简洁易用.

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

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