【问题标题】:How to set a single, main title above all the subplots with Pyplot?如何使用 Pyplot 在所有子图之上设置一个主标题?
【发布时间】:2011-10-27 07:47:05
【问题描述】:

我正在使用pyplot。我有 4 个子图。如何在所有子图上方设置一个主标题? title() 将其设置在最后一个子图之上。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    使用pyplot.suptitleFigure.suptitle

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig=plt.figure()
    data=np.arange(900).reshape((30,30))
    for i in range(1,5):
        ax=fig.add_subplot(2,2,i)        
        ax.imshow(data)
    
    fig.suptitle('Main title') # or plt.suptitle('Main title')
    plt.show()
    

    【讨论】:

    • suptitle 一起使用。尽管如此,我还是看到了你的“无耻黑客”! :)
    • 注意,它是plt.suptitle() 而不是plt.subtitle()。我一开始并没有意识到这一点,并得到了一个令人讨厌的错误! :D
    【解决方案2】:

    在将其应用于我自己的情节时,我发现几点很有用:

    • 我更喜欢使用fig.suptitle(title) 而不是plt.suptitle(title) 的一致性
    • 使用fig.tight_layout() 时,标题必须用fig.subplots_adjust(top=0.88) 移动
    • 查看关于字体大小的回答below

    示例代码取自 matplotlib 文档中的 subplots demo,并使用主标题进行了调整。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Simple data to display in various forms
    x = np.linspace(0, 2 * np.pi, 400)
    y = np.sin(x ** 2)
    
    fig, axarr = plt.subplots(2, 2)
    fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)
    
    axarr[0, 0].plot(x, y)
    axarr[0, 0].set_title('Axis [0,0] Subtitle')
    axarr[0, 1].scatter(x, y)
    axarr[0, 1].set_title('Axis [0,1] Subtitle')
    axarr[1, 0].plot(x, y ** 2)
    axarr[1, 0].set_title('Axis [1,0] Subtitle')
    axarr[1, 1].scatter(x, y ** 2)
    axarr[1, 1].set_title('Axis [1,1] Subtitle')
    
    # # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
    plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
    plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)
    
    # Tight layout often produces nice results
    # but requires the title to be spaced accordingly
    fig.tight_layout()
    fig.subplots_adjust(top=0.88)
    
    plt.show()
    

    【讨论】:

    • 仅仅添加figure.suptitle() 是不够的,因为子图的标题会与suptitile 混合,fig.subplots_adjust(top=0.88) 很好。
    【解决方案3】:

    如果您的子图也有标题,您可能需要调整主标题大小:

    plt.suptitle("Main Title", size=16)
    

    【讨论】:

    • 在 python 2.7 中它是 fontsize 而不是 sizeplt.suptitle("Main Title", fontsize=16)
    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多