在绘制子图时,如何在matplotlib python中解压元组?

2024-09-29 17:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

fig,((ax1,ax2,ax3),(ax4,ax5,ax6),(ax7,ax8,ax9)) = plt.subplots(3,3,sharex=True,sharey=True)

lineardata=np.array([1,2,3,4,5])

ax5.plot(lineardata,'-')

我了解到“plt.subplot”函数返回一个元组,但我无法理解它们是如何在fig中解包的,ax1、ax2、ax3、ax4、ax5、ax6、ax7、ax8、ax9


Tags: truefigpltax1ax3ax4ax2subplots
2条回答

为了解释how they are unpacked in the fig, ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8,ax9,我们从一个简单的代码开始:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(3, 3, sharex=True, sharey=True)

现在我们通过使用python控制台(python解释器)来发现ax

in[0]: ax
Out[0]: 
array([[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]], dtype=object)

它返回一个维度为3 x 3的数组:

然后,我们分享您的代码片段

((ax1,ax2,ax3),(ax4,ax5,ax6),(ax7,ax8,ax9)) = ax

(ax1,ax2,ax3),(ax4,ax5,ax6),(ax7,ax8,ax9) = ax

反过来,我们想探索ax的内容是如何分布在您提供的对象名称上的

这是通过在后面的代码中探索=的左侧和右侧之间的关系来实现的,并且再次使用python控制台:

In[1]: ax1==ax[0][0]
Out[1]: True

等等

In[2]: ax2==ax[0][1]
Out[2]: True
In[3]: ax3==ax[0][2]
Out[3]: True
In[4]: ax4==ax[1][0]
Out[4]: True
In[5]: ax5==ax[1][1]
Out[5]: True
In[6]: ax6==ax[1][2]
Out[6]: True
In[7]: ax7==ax[2][0]
Out[7]: True
In[8]: ax8==ax[2][1]
Out[8]: True
In[9]: ax9==ax[2][2]
Out[9]: True

所以我们推断,映射已经完成,就好像

array([[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]], dtype=object)
=
array([[ax1, ax2, ax3],
       [ax4, ax5, ax6],
       [ax7, ax8, ax9]], dtype=object)

因此,映射依赖于将给定对象的序列与第一行、第二行直到最后一行的对象序列相匹配

我们还推断映射是通过生成的数组完成的,并且不是subplots函数本身的一部分

最后,我们应该提到,结果数组ax是一个numpy.ndarray,即使您没有将numpy导入它

我希望上面的插图能说明你的问题

等待你的评论

matplotlib.pyplot.subplots返回一个元组,其中包含一个figure对象和一个axis对象数组:

from matplotlib import pyplot as plt

fig,axs = plt.subplots()
axs[0].plot(...)

作为docs国:

Return values:

fig = Figure

ax = axes.Axes or array of Axes

相关问题 更多 >

    热门问题