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

How the .add_subplot(nrows, ncols, index) works?

我正在使用 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

我得到这个输出

我的问题是最后一个参数是如何工作的。为什么 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)

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

如果有人能解释索引的工作原理,我将不胜感激。研究了好久还是没搞定

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

在上面的例子中,使用 212 的原因是因为前三行 ax1ax2ax3 将子图添加到 2 行和3 列网格。如果211用于第四个子图(ax4),它将与(231), (232)(233)的第一行重叠。这可以在下面的第二张图中看到 ax4 与下面的 3 个子图重叠。这就是为什么 ax4 在 2 行 1 列图的第二行使用 (212) 添加,而不是将其添加到使用 (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)

如果您使用 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)