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

时间:2018-12-30 13:45:20

标签: python matplotlib plot subplot

我尝试使用matplotlib.pyplot调整四个图像,如下所示:

| plot1 | plot2|
|    plot3     |
|    plot4     |

我发现的大多数示例都涵盖了以下三个情节:

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

这成功地绘制了三个图(但是,我不知道如何ax3完成它)。现在,我想将图4添加到该布置中。无论我尝试什么,我都无法成功。

您能指导我如何实现吗?

2 个答案:

答案 0 :(得分:3)

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

医生说

  

在网格中创建子图。网格由形状指定,在loc的位置,跨行跨,在每个方向上的colspan单元格。 loc的索引从0开始。

首先,您在此处根据行数(3,2)定义大小。然后,为特定子图定义起始(行,列)位置。然后,分配该特定子图所跨越的行数/列数。行跨度和列跨度的关键字分别为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()

enter image description here

答案 1 :(得分:1)

您提供给子图的整数实际上是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

  

3位整数或三个独立的整数描述   子图的位置。如果三个整数是nrows,ncols和   索引顺序,子图将在网格上取得索引位置   带有nrows行和ncols列。索引从左上方的1开始   并向右增加。

     

pos是一个三位数的整数,其中第一位数是   行,第二个是列数,第三个是索引   子图。即fig.add_subplot(235)与fig.add_subplot(2,   3,5)。请注意,此格式的所有整数必须小于10   工作。

321 312