There is a constant distance between the legend bounding box and the axes by default. This is set via the borderaxespad
parameter. This defaults to the rc value of rcParams["legend.borderaxespad"]
, which is usually set to 0.5
(in units of the fontsize).
So essentially you get the behaviour you're asking for for free. Mind however that you should specify the loc
to the corner of the legend from which that padding is to be taken. I.e.
import numpy as np
import matplotlib.pyplot as plt
for figsize in [(5,4), (5,9)]:
fig, ax = plt.subplots(figsize=figsize)
ax.plot([1,2,3], label="label")
ax.legend(loc="lower left", bbox_to_anchor=(0,1))
plt.show()

For more detailed explanations on how to position legend outside the axes, see How to put the legend out of the plot. Also relevant: How to specify legend position in matplotlib in graph coordinates