I would like to be able to add legends to the figure, making sure they don’t overlap with any of the axes. In my use case, I don’t know how many axes there are, nor if tight_layout
is True
or not.
The following example allows to see the problem
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
handles = [Line2D([], [], color=f"C{i}", solid_capstyle="butt") for i in range(3)]
fig, axes = plt.subplots(1, 3, figsize=(15, 5), tight_layout=True)
for i, ax in enumerate(axes):
ax.plot([0, 1], [1, 2], color=f"C{i}")
fig.legend(handles, ["1", "2", "3"], title="legend", bbox_to_anchor=(1, 0.5), loc="center left")
fig.savefig("plot.png")
The saved figure
How I would like it to look like (this is how it looks like in the jupyter notebook)
I know I could do something like
fig.subplots_adjust(left=0.05, right=0.8)
fig.legend(handles, ["1", "2", "3"], title="legend", bbox_to_anchor=(0.8, 0.5), loc="center left")
but the function I’m writing goes into a package and I don’t know if users are going to pass a figure with constrained_layout
equals to True
or not.
- I’ve seen this PR ENH: allow fig.legend outside axes... by jklymak · Pull Request #19743 · matplotlib/matplotlib · GitHub but it’s not merged.
- I’ve also tried doing
legend.set_in_layout(True)
but it didn’t change anything
My questions are
- Do you know if it’s possible to get legends drawn on the figure, without overlapping the axes is possible in a general way? (either with or without
tight_layout
active) - If not, do you think this will be possible in the near future?
Thanks a lot!
Matplotlib version: 3.6.2