【问题标题】:How can I plot four subplots with different colspans?如何绘制具有不同 colspans 的四个子图?
【发布时间】:2019-05-27 10:27:05
【问题描述】:

我尝试使用matplotlib.pyplot 来适应四张图片,如下所示:

| plot1 | plot2|
|    plot3     |
|    plot4     |

我发现的大多数示例都包含以下三个图:

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

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

您能指导我如何实现它吗?

【问题讨论】:

    标签: python matplotlib plot subplot


    【解决方案1】:

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

    文档说

    在网格中创建一个子图。网格由形状指定,在 loc 的位置,在每个方向上跨越 rowspan,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()
    

    【讨论】:

      【解决方案2】:

      您提供给 subplot 的整数实际上是 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 工作。

      【讨论】:

      • 非常感谢!整个身材比我预想的要小,怎么能让它枯死或者变高?
      • 我想我找到了我的 cmets 的答案:plt.figure(num=2, figsize=(15, 20), dpi=80, facecolor='w', edgecolor='k') plt.subplots_adjust(hspace=0.3,bottom=0.3)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      相关资源
      最近更新 更多