Faster version of function: tight_layout


This is related to [Bug]: Savefig slow with subplots · Issue #26150 · matplotlib/matplotlib · GitHub in which I use fig.tight_layout() to remove excess white-space from a figure and make it look nice, which takes around 3 seconds when having 10 rows and 3 columns of sub-plots. This is a problem in a real-time / low-latency application.

I can manually remove the excess white-space by calling subplots_adjust which is near-instant to run, but I need to know the proper arguments - which I can get from calling tight_layout once. The problem is that the size of my plots vary in the number of columns and rows, so I require different arguments to subplots_adjust. So it is much easier to call tight_layout to automatically adjust the white-space - but it is very slow.

Since tight_layout is so slow, I wonder how exactly it works. Does it iterate recursively through all children and artists in the figure, to find the bounds of all artists and thereby the bounds of the entire figure?

In my case the sub-plots don’t have any “protruding” artists. Everything is contained within the sub-plots, so it doesn’t seem to be necessary to iterate recursively through all artists to make sure they don’t transgress the sub-plot bounds.

Would it be possible to add an argument to tight_layout to make a simpler and faster recursion through the artists, that doesn’t recurse deep into the sub-plots, but merely assumes there are no “protruding” artists in the sub-plots?

Perhaps this could also make it faster to run tight_layout on simpler plots that don’t have any sub-plots? It typically takes me around 200 milli-seconds to run tight_layout on simple plots - which is often a significant part of the plotting time.

Also note that in my experiments, calling fig.tight_layout() is slightly faster than setting either Figure(layout='tight') or Figure(layout='constrained'), and the latter also gives uneven spacing between the sub-plots.