You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Docs: performance discussion of tight_layout #16550
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.
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.
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.
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 ?
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.
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)
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.
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.
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.
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.
Activity
ImportanceOfBeingErnest commentedon Feb 18, 2020
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:
Which gives the following timings on my machine:
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.
arn-all commentedon Feb 18, 2020
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 ?
ImportanceOfBeingErnest commentedon Feb 18, 2020
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?
arn-all commentedon Feb 18, 2020
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.
ImportanceOfBeingErnest commentedon Feb 18, 2020
Indeed. You can call
tight_layoutonce, get the subplot parameters, store them and reuse later.(Note the same won't work with constrained_layout)
tacaswell commentedon Feb 18, 2020
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.
jklymak commentedon Feb 18, 2020
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.
anntzer commentedon Feb 21, 2020
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.
jklymak commentedon Nov 13, 2021
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.
davidgilbertson commentedon Feb 27, 2023
For future travellers, I do the following to get constrained layout to run only on resize (showing a figure in a separate window):
Someone please tell me if there's a smarter way to do this.
Hvass-Labs commentedon Jun 19, 2023
I had problems with
tight_layouttaking a whopping 3 seconds to run for a fairly simple plot with 3*10 sub-plots! And many of the args likeconstrained_layoutdon't seem to be available forFigureobjects.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: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_layoutwas faster, but this may be a workable solution for many cases.