gpt4 book ai didi

Python - matplotlib - subplot() 和 subplots() 之间的区别

转载 作者:可可西里 更新时间:2023-11-01 09:50:32 30 4
gpt4 key购买 nike

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

在阅读来自 https://matplotlib.org/ 的文档后,我没有在其他任何地方找到此解释。我推断,使用这两种方法,您都可以根据需要创建任意数量的图形和绘图……所以对我来说,它们似乎是完全相同的东西,它们只是处理绘图、轴等的方式不同……还是我错了?

顺便说一句,我在 jupyter notebook 中使用 python3,如果它有任何不同的话。

最佳答案

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,它允许您轻松访问每个子图:

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

2。 matplotlib.pyplot.subplot()

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

# 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的内置方法:

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() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52214776/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com