代码之家  ›  专栏  ›  技术社区  ›  Jiadong

如何调整子图间距并在matplotlib中放置y标签?

  •  0
  • Jiadong  · 技术社区  · 6 年前

    我必须使用matplotlib生成以下布局。

    fig = plt.figure(figsize=(15,9))
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 0], 1, 1 )
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 1], 1, 1 )
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 2], 1, 3 )
    

    enter image description here 放置公用标签 由红色标记指示。我被困在这一点上。谁能给我一些指导?谢谢您!

    1 回复  |  直到 6 年前
        1
  •  1
  •   Mr. T Andres Pinzon    6 年前

    如果标签不长,只需将其添加到中间的图形中并使用 tight_layout 要格式化它:

    fig = plt.figure(figsize=(15,9))
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 0], 1, 1 )
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 1], 1, 1 ) 
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 2], 1, 3 )
        if i == 1:
            ax.set_ylabel("label for all")
    
    plt.tight_layout()
    plt.show()
    

    紧凑的布局 会曲解中间一排的高度。在这种情况下,我们可以简单地将文本替换为以后的较长版本:

    fig = plt.figure(figsize=(15,9))
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 0], 1, 1 )
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 1], 1, 1 ) 
    for i in range(3):
        ax = plt.subplot2grid((3, 5), [i, 2], 1, 3 )
        if i == 1:
            mylabel = ax.set_ylabel("dummy")
    
    plt.tight_layout()
    
    mylabel.set_text("not a dummy any more but a very very very loooooooooooooooooong label")
    plt.show()
    

    样本输出: enter image description here