I know that in Python's matlplotlib legend function we can adjust the spacing between the labels using "labelspacing", for example:
lgd = ax.legend(..., labelspacing=2)
but can I have a more custom spacing between labels where for example the space between the first two labels is 2 and between the 2nd and 3rd label is 3, and so on?
Doing so would allow me to line up the labels with the lines in my plot nicely (outside the plot).
Looks like there's no easy way to do this, as plt.legend uses a VPacker to manage the entries in the legend: https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/legend.py#L713
VPacker only supports a single sep for all entries:
http://matplotlib.org/api/offsetbox_api.html#matplotlib.offsetbox.VPacker
Have you thought about drawing the legend manually?
(E.g. drawing a white box with patches.Rectangle and the text with plt.text)
That would probably also make it much easier to align the items with the contents of your plot.
For example, like this:
import matplotlib.pyplot as plt
from matplotlib import patches
rect = patches.Rectangle((0.7, 0.35), 0.2, 0.3, facecolor='white')
plt.gca().add_patch(rect)
plt.text(0.75, 0.58, 'my')
plt.text(0.75, 0.5, 'custom')
plt.text(0.75, 0.42, 'legend')

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With