For the automatic positioning of a single legend in a figure
with many axes, like those obtained with subplots()
, the following solution works really well:
plt.legend(lines, labels, loc = 'lower center', bbox_to_anchor = (0, -0.1, 1, 1), bbox_transform = plt.gcf().transFigure)
With bbox_to_anchor
and bbox_transform=plt.gcf().transFigure
, you are defining a new bounding box of the size of your figure
to be a reference for loc
. Using (0, -0.1, 1, 1)
moves this bounding box slightly downwards to prevent the legend to be placed over other artists.
OBS: Use this solution after you use fig.set_size_inches()
and before you use fig.tight_layout()