.add_subplot(nrows, ncols, index) 如何工作?

Meh*_*CER 2 python matplotlib subplot

我正在 matplotlib 的add_subplot()函数中创建一个图形。

当我运行这个

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(212) # why not 211
Run Code Online (Sandbox Code Playgroud)

我得到这个输出

在此处输入图片说明

我的问题是这最后一个论点是如何运作的。为什么 ax4 是 212 而不是 211,因为第二行只有一个图?

如果我使用 211 而不是 212 运行,如下所示:

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(211)
Run Code Online (Sandbox Code Playgroud)

我得到这个输出,其中 Plot 4 放在第一行的 Plot 2 上。

在此处输入图片说明

如果有人能解释索引是如何工作的,我将不胜感激。花了不少时间研究还是没搞懂。

She*_*ore 5

212这里使用的索引是有意的。这里前两个索引表示 2 行和 1 列。当第三个数字为 1(211)时,表示在第一行添加子图。当第三个数字为 2(212)时,表示在第二行添加子图。

的是,在上述例子中,原因212是使用是因为第一三行ax1ax2ax3增加了副区到一个2行和第3列的网格。如果211被用于第四副区(ax4),它会与第一排重叠(231), (232)(233)。这可以在下面的第二个图中看到,您可以看到ax4重叠的基础 3 个子图。这就是在ax42 行 1 列图的第二行(212)中添加using而不是将其添加到 using 的第一行的原因(211)

如果使用212,则会得到以下输出

fig = plt.figure()

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(212)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果使用211,则会得到以下输出。如您所见,ax4覆盖了 3 个子图。

fig = plt.figure()

ax1 = fig.add_subplot(231)
ax2 = fig.add_subplot(232)
ax3 = fig.add_subplot(233)
ax4 = fig.add_subplot(211)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明