Skip to content

Docs: performance discussion of tight_layout #16550

Closed

Description

@arn-all

Problem

I remarked the execution of plt.tight_layout() was a bottleneck in a code I'm writting. Though, I needed it to get a proper layout adjustment of my multi-plot figure.

To my knowledge, the docs do not mention any performance concern, or alternative to tight_layout. I found a nice alternative by using plt.subplots(constrained_layout=True), with a gain of roughly 50% in computation time and an (almost) visually similar output.

Simple demonstration

import matplotlib.pyplot as plt
def with_constrained_layout(): 
    x = [1, 2, 3] 
    y = [1, 4, 9] 
    fig, axes = plt.subplots(2, constrained_layout=True) 
    axes[0].scatter(x,y) 
    axes[1].scatter(x,y) 
    plt.close() 
                          

def with_tight_layout(): 
    x = [1, 2, 3] 
    y = [1, 4, 9] 
    fig, axes = plt.subplots(2) 
    axes[0].scatter(x,y) 
    axes[1].scatter(x,y) 
    plt.tight_layout() 
    plt.close()                            

%timeit with_tight_layout()
251 ms ± 54.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit with_constrained_layout()                               
124 ms ± 12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Output using tight_layout :
Figure_tight_layout

Output using constrained_layout :
Figure_constrained_layout

Proposed solution

I think this should be discussed somewhere in the docs, but I'm not familiar with the internals of matplotlib and the reasons why tight_layout is so slow (I guess the two functions are not equivalent in general, just give a similar output in my case). There are also probably other approaches that might perform much better, that I'm not aware of.

Matplotlib version

  • Matplotlib version : 3.0.2
  • Python version : 3.7.6
  • IPython version : 7.2.0

Activity

  1. ImportanceOfBeingErnest commented on Feb 18, 2020

    @ImportanceOfBeingErnest
    Member

    Constrained_layout is not actually faster than tight_layout. In the code above, constrained_layout is not actually applied, because the figure is never drawn.

    Consider the following:

    import matplotlib.pyplot as plt
    
    x = [1, 2, 3] 
    y = [1, 4, 9]
        
    def with_constrained_layout(use=True, draw=True): 
        fig, axes = plt.subplots(2, constrained_layout=use) 
        axes[0].scatter(x,y) 
        axes[1].scatter(x,y)
        if draw:
            fig.canvas.draw()
        plt.close()
                              
    
    def with_tight_layout(use=True, draw=True): 
        fig, axes = plt.subplots(2) 
        axes[0].scatter(x,y) 
        axes[1].scatter(x,y)
        if use:
            fig.tight_layout() 
        if draw:
            fig.canvas.draw()
        plt.close()
    

    Which gives the following timings on my machine:

    # Do not use layout manager
    %timeit with_tight_layout(use=False, draw=False)          #   19.5 ms
    %timeit with_tight_layout(use=False, draw=True)           #   65.7 ms
    
    %timeit with_constrained_layout(use=False, draw=False)    #   19.9 ms
    %timeit with_constrained_layout(use=False, draw=True)     #   66.3 ms      
    
    # use layout manager
    %timeit with_tight_layout(use=True, draw=False)           #   77.5 ms
    %timeit with_tight_layout(use=True, draw=True)            #  108   ms
      
    %timeit with_constrained_layout(use=True, draw=False)     #   21.0 ms
    %timeit with_constrained_layout(use=True, draw=True)      #  149   ms      
    

    You see that unless you actually draw the figure, the time is the same as when not applying any layout manager at all (~20 ms). While if you apply constrained_layout and draw the figure it actually slower than tight layout (150 ms vs. 108 ms).


    That being said, a more complete comparison between the two may be worth adding to the docs. I suppose that could be done in the constrainedlayout_guide tutorial.

  2. arn-all commented on Feb 18, 2020

    @arn-all
    Author

    Oh, my mistake. Thanks for clarifying !

    Then the 50% difference is between using a layout manager or not.
    I think it'd be a good idea to warn users that using either tight_layout or constrained_layout will induce a significant overhead.

    Can you think of a faster alternative/strategy than using these functions ?

  3. ImportanceOfBeingErnest commented on Feb 18, 2020

    @ImportanceOfBeingErnest
    Member

    I wouldn't necessarily call the ~50ms difference a "significant" overhead, but yes, it could well be mentionned somewhere.

    What exact use case do you have where this difference is a bottleneck?

  4. arn-all commented on Feb 18, 2020

    @arn-all
    Author

    What I'm doing is a series of subplots to correlate a timeseries of images (imread/imshow) and a graph on the side (plot/scatter). I use tight_layout to adapt the dimensions of both components on every figure I save.

    I'm now considering a much better strategy, that would be considering one figure with few dynamic components. The layout is setup once, and only the dynamic components are modified in a loop, instead of seeing it as a new figure that is created and fill-in on every loop.

  5. ImportanceOfBeingErnest commented on Feb 18, 2020

    @ImportanceOfBeingErnest
    Member

    Indeed. You can call tight_layout once, get the subplot parameters, store them and reuse later.

    fig.tight_layout()
    dic = {par : getattr(fig.subplotpars, par) for par in ["left", "right", "bottom", "top", "wspace", "hspace"]}
    
    # at some other point
    fig.subplots_adjust(**dic)
    

    (Note the same won't work with constrained_layout)

  6. tacaswell commented on Feb 18, 2020

    @tacaswell
    Member

    The layout is setup once, and only the dynamic components are modified in a loop, instead of seeing it as a new figure that is created and fill-in on every loop.

    If you are running in a tight-loop where Matplotlib's performance is your bottle neck, not re-creating the Figure, Axes, and ticks every loop will also likely save you significant time.

  7. jklymak commented on Feb 18, 2020

    @jklymak
    Member

    You can run constrained_layout on the original plot and then turn it off for subsequent plots. Probably the same for tight_layout. I’m pretty sure the constrained-layout docs are clear about the performance issues.

  8. anntzer commented on Feb 21, 2020

    @anntzer
    Contributor

    Profiling the code a bit shows that this is (at least to some extent) due to the usual slow tick creation and insufficient lazyfication of tick instances, so I think this may be fixable.

  9. modified the milestones: 3.2-doc, v3.3-doc on Jul 17, 2020
  10. modified the milestones: v3.3-doc, v3.5.0 on Jan 28, 2021
  11. modified the milestones: v3.5.0, v3.6.0 on Sep 25, 2021
  12. jklymak commented on Nov 13, 2021

    @jklymak
    Member

    I'm going to close this. Hopefully it is clear to people that doing automatic axes adjustments will come at a cost in terms of cpu cycles.

  13. davidgilbertson commented on Feb 27, 2023

    @davidgilbertson
    Contributor

    For future travellers, I do the following to get constrained layout to run only on resize (showing a figure in a separate window):

    def on_resize(event=None):
        fig.set_constrained_layout(True)
        fig.get_layout_engine().execute(fig)
        fig.set_constrained_layout(False)
    
    fig.canvas.mpl_connect("resize_event", on_resize)
    on_resize()

    Someone please tell me if there's a smarter way to do this.

  14. Hvass-Labs commented on Jun 19, 2023

    @Hvass-Labs

    I had problems with tight_layout taking a whopping 3 seconds to run for a fairly simple plot with 3*10 sub-plots! And many of the args like constrained_layout don't seem to be available for Figure objects.

    My final solution was mentioned above in #16550 (comment), but it didn't catch my eye on a first read, and I ended up spending some time trying to figure this out, so I thought I would elaborate a bit and write my process.

    If your layout is always going to be the same, then a simple solution is to do the plotting, then call tight_layout, print the adjusted parameters, and manually use them the next time you need to make the plot. Something like this:

    # Setup figure with many sub-plots.
    fig = Figure(figsize=(10, 6))
    axs = fig.subplots(ncols=3, nrows=10, sharex='col')
    
    # Do the plotting ...
    
    # Adjust layout. This takes 3 seconds for me!
    fig.tight_layout()
    
    # Print the adjusted layout parameters.
    print(fig.subplotpars)
    
    # Next time avoid calling `tight_layout` and just use the layout parameters.
    fig.subplots_adjust(bottom=0.04, top=0.94, hspace=0.2,
                        wspace=0.05, left=0.07, right=0.985)
                        
    # Or perhaps you can just call this.
    fig.subplots_adjust(fig.subplotpars)
    

    I round these parameters slightly, to hopefully accommodate for small variations in the plots without breaking the layout. It's not an ideal solution, and it would be much better if tight_layout was faster, but this may be a workable solution for many cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions