Explain Codes LogoExplain Codes Logo

How to put the legend outside the plot

python
matplotlib
legend-positioning
customization
Anton ShumikhinbyAnton ShumikhinยทNov 12, 2024
โšกTLDR

To quickly move your legend outside your matplotlib plot, use the legend() function along with the bbox_to_anchor parameter. Coordinates can be set for absolute precision:

import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 3, 2], label='Trend') # Legend outside: Right & above the plot. Yes, this is an eviction! ๐Ÿ โžก๏ธ plt.legend(loc='upper left', bbox_to_anchor=(1, 1)) plt.show()

Changing the bbox_to_anchor values allows you to tweak the precise location of the evicted legend. Perfect for those sudden landlord tendencies! ๐Ÿก

Full control over legend positioning and aesthetics

Customize legend placement with ax.set_position()

Avoid an overlapping or clipping legend by resizing the plot itself using ax.set_position():

import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 3, 2], label='Data trend') # It's like Tetris but with a plot and legend! ax.set_position([0.1, 0.1, 0.65, 0.8]) # Position the legend outside ax.legend(loc='upper left', bbox_to_anchor=(1, 1)) plt.show()

Make comprehensive legends readable with fontsize

Readability can take a hit with large legends. Adjust the fontsize to make mature decisions about space allocation!

ax.legend(loc='upper left', bbox_to_anchor=(1, 1), fontsize='small') # Good things come in SMALL packages!

Prevent overrun with plt.tight_layout

For nicely packed visuals, apply the plt.tight_layout method. Remember, we're making art, not a sandwich!

plt.tight_layout(rect=[0, 0, 0.75, 1]) # Your legend wasn't raised to be sloppy!

Use subplots and gridspec_kw for fine-tuning

If you're uncompromising about your main plot, dedicate a subplot to the legend:

fig, (ax, lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4, 1]}) lax.legend(*ax.get_legend_handles_labels(), loc='center') lax.axis('off') # It's less of a subplot, more of a VVIP legend balcony! ๐Ÿพ

Advanced font customization for your keen eyes

For typography enthusiasts, Matplotlib's font_manager offers the keys to the font kingdom:

from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('xx-small') # If you can control font size, are you a font God?! ๐Ÿง™โ€โ™‚๏ธ # Command the legend to respect your font authority ax.legend(prop=fontP)

Across-the-board consistency with fig.legend

For the perfectionists who seek uniformity across subplots, turn to fig.legend:

fig.legend(loc='center right', bbox_to_anchor=(1, 0.5)) # Uniformity is the secret ingredient of a good figurewide legend soup! ๐Ÿฒ