【问题标题】:How to use matplotlib tight layout with Figure?如何使用 matplotlib 紧密布局与 Figure?
【发布时间】:2012-03-25 02:01:21
【问题描述】:

我找到了 pyplot 的 tight_layout 函数并想使用它。在我的应用程序中,我将 matplotlib 绘图嵌入到 Qt GUI 中并使用图而不是 pyplot。有什么方法可以在那里申请tight_layout 吗?如果我在一个图中有多个轴,它也可以工作吗?

【问题讨论】:

    标签: python matplotlib figure


    【解决方案1】:

    只需像往常一样拨打fig.tight_layout()。 (pyplot 只是一个方便的包装器。在大多数情况下,您只是使用它来快速生成图形和轴对象,然后直接调用它们的方法。)

    QtAgg 后端和默认后端之间应该没有区别(或者如果有,那是一个错误)。

    例如

    import matplotlib.pyplot as plt
    
    #-- In your case, you'd do something more like:
    # from matplotlib.figure import Figure
    # fig = Figure()
    #-- ...but we want to use it interactive for a quick example, so 
    #--    we'll do it this way
    fig, axes = plt.subplots(nrows=4, ncols=4)
    
    for i, ax in enumerate(axes.flat, start=1):
        ax.set_title('Test Axes {}'.format(i))
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
    
    plt.show()
    

    紧凑布局之前

    紧凑布局后

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=4, ncols=4)
    
    for i, ax in enumerate(axes.flat, start=1):
        ax.set_title('Test Axes {}'.format(i))
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
    
    fig.tight_layout()
    
    plt.show()
    

    【讨论】:

    • 完美,如此简单!谢谢,现在可以了。并非一切正常的唯一情况是使用科学格式 - 1e5(或类似的)对于 x 轴部分不可见。我以某个角度旋转标签。
    • 我已经尝试过了,当尝试将其与设置为 pyplot.figure() ax 对象的 mpl_toolkits.basmap 一起使用时,我得到了 ValueError: max() arg is an empty sequence。这是一个错误,还是一起使用这个和basemap 的限制?
    • @shootingstars - 你能举一个更完整的例子吗?它应该适用于底图。 (尽管您应该查看 cartopy 以获得更现代的 matplotlib 映射工具包。)
    • @shootingstars - 这可能是因为您制作的轴不是子图。 tight_layout 所做的只是计算 subplots_adjust 的参数,因此 tight_layout 仅适用于子图。使用fig, ax = plt.subplots()ax = fig.add_subplot(1,1,1) 而不是手动指定轴的范围,它应该可以正常工作。 (顺便说一下,在这种情况下,较新版本的 matplotlib 会给出更多信息错误。)
    • 您的fig = Figure() 建议将导致tight_layout 提高ValueError,除非以其他方式实例化轴。 subplots 是创建坐标轴和图形实例的正确方法。
    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 2021-01-28
    • 2021-07-24
    • 2016-05-25
    • 2021-01-11
    • 2018-12-14
    • 2018-06-02
    • 2022-01-18
    相关资源
    最近更新 更多