【问题标题】:How to adjust subplots spacing and to place y labels in matplotlib?如何调整子图间距并在 matplotlib 中放置 y 标签?
【发布时间】:2018-11-25 12:26:09
【问题描述】:

我必须使用 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 )

我想在第二列和第三列之间添加一些空格以放置一个由红色标记指示的通用 ylabel。我被困在这一点上。任何人都可以给我一些指导吗?谢谢!

【问题讨论】:

    标签: python-3.x matplotlib subplot


    【解决方案1】:

    如果你的标签不长,你可以简单的将它添加到中间的图中,并使用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()
    

    但这不适用于很长的标签,因为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:
            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()
    

    示例输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多