Reputation: 63
I'm making a plot with a GUI that has a long legend handle placed above the axes. The legend is wider than the axes so I'm attempting to expand the axes to match the width of the legend buy using fig.tight_layout().
However, I've found that when tight_layout() is called, this reduces the width of my axes instead of filling the space under the legend as expected.
Here is my figure before calling tight_layout().
And after calling tight_layout().
Surprisingly, I found that the axes width decreases after every tight_layout() call. Is there a problem with calling tight_layout() when the legend is wider than the axes? This doesn't happen when the legend width is smaller than the figure.
Here is the code to reproduce the figures and behavior.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# make dataframe with random data
np.random.seed(seed=7)
data1 = np.random.normal(size=100)
name1 = 'handle_with_a_really_really_really_really_long_name'
d = {name1: data1}
df = pd.DataFrame(data=d)
# plotting stuff
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(111)
df.plot(ax=ax, kind='hist')
ax.legend(loc='lower left', bbox_to_anchor=(-0.04, 1.05))
# tight layout calls to reduce axis width
#fig.tight_layout()
#fig.tight_layout()
#fig.tight_layout()
Upvotes: 1
Views: 1618
Reputation: 63
Thanks to Jody's response, I realized the legend size was larger than the figure. This is what caused the shrinking axes as described by Jody.
The solution is to resize the figure in this case, then use tight layout. That will fix shrinking axes behavior.
Upvotes: 0
Reputation: 5912
The axes tries to make itself small enough that none of its artists overlap any other axes or the edge of the figure. In this case there is nothing it can do to make itself small enough to not spill over the edge of the figure, but it keeps trying.
Why do you want to call tight_layout? You could take the legend out of the tight_layout leg=legend()
, leg.set_in_layout(False)
, and then call tight_layout
to get the widths right, and then use subplots_adjust
to make enough room at the top. But you could also just make the label a more reasonable length.
Upvotes: 1