如何绘制四个具有不同 colspans 的子图?

How can I plot four subplots with different colspans?

我尝试使用 matplotlib.pyplot 来拟合四个图像,如下所示:

| plot1 | plot2|
|    plot3     |
|    plot4     |

我找到的大多数示例都包含如下三个图:

ax1 = plt.subplot(221)
ax2 = plt.subplot(222)
ax3 = plt.subplot(212)

这成功绘制了三个图(但是,我不明白 ax3 是如何完成的)。现在,我想将情节 4 添加到此安排中。无论我尝试什么,我都无法成功。

能否请您指导我如何实现它?

您提供给子图的整数实际上是 3 个部分:

  • 第一个数字:行数
  • 第二位:列数
  • 第三位:索引

因此,对于每次调用子图,我们指定应如何划分绘图区域(使用行和列),然后指定将绘图放入哪个区域(使用索引),请参见下图。

ax1 = plt.subplot(321)  # 3 rows, 2 cols, index 1: col 1 on row 1
ax2 = plt.subplot(322)  # 3 rows, 2 cols, index 2: col 2 on row 1
ax3 = plt.subplot(312)  # 3 rows, 1 cols, index 2: col 1 on row 2
ax4 = plt.subplot(313)  # 3 rows, 1 cols, index 3: col 1 on row 3

来自docs

Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right.

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.

您可以使用 subplot2grid。真的很方便。

文档说

Create a subplot in a grid. The grid is specified by shape, at location of loc, spanning rowspan, colspan cells in each direction. The index for loc is 0-based.

首先,您在这里根据行数和列数 (3,2) 定义大小。然后为特定子图定义起始(行、列)位置。然后分配该特定子图跨越的 rows/columns 的数量。行和列跨度的关键字分别为 rowspancolspan

import matplotlib.pyplot as plt

ax1 = plt.subplot2grid((3, 2), (0, 0), colspan=1)
ax2 = plt.subplot2grid((3, 2), (0, 1), colspan=1)
ax3 = plt.subplot2grid((3, 2), (1, 0), colspan=2)
ax4 = plt.subplot2grid((3, 2), (2, 0), colspan=2)
plt.tight_layout()