Explain Codes LogoExplain Codes Logo

Adding a matplotlib legend

python
matplotlib
legend
plotting
Alex KataevbyAlex Kataev·Sep 28, 2024
TLDR

To incorporate a legend into your matplotlib chart, it's as simple as calling plt.legend() right after plotting your data. Make sure every data series has a distinct label attribute. This is a straightforward example:

import matplotlib.pyplot as plt # Plot data with magnificent labels for the mighty legend plt.plot([1, 2, 3], label='Rising Phoenix') plt.plot([3, 2, 1], label='Falling Icarus') # Bestow the legend in the 'best' mansion plt.legend(loc='best') # Time to party! plt.show()

Voilà! Your chart now has a cleverly-positioned legend that labels each line. Change loc to move the legend around.

How to use matplotlib's legend function effectively

When gracing your plots with legends, remember good ol' label= inside plot() - it's your line's VIP pass. For complete control, plt.gca().legend() is your secret spell to add legends without creating new mystical variables.

Labelling lines for legends

Sometimes, arranging a meeting with plot() for labels isn't an option. Instead, deliver a list of labels directly to plt.legend():

plt.plot([1, 2, 3]) plt.plot([3, 2, 1]) # Custom labels for the legend, because everyone needs a name plt.legend(['Upward Bound', 'Downward Dog']) plt.show()

Command the legend's location

Summon the loc parameter to specify positions like 'upper left', 'lower right', or 'center'. For house parties where the best seat changes, let matplotlib decide with 'best'.

When there's more than one subplot

For crowded gatherings with multiple subplots, legends become vital name-tags:

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5)) ax1.plot([...], label='Left Squad') ax2.plot([...], label='Right Crew') ax1.legend() ax2.legend() # Let's see who gets more votes! plt.show()

Advanced features for distinguished guests

Setting the stage

A great show needs a great stage. plt.figure(figsize=(width, height)) sets the stage size ensuring all your stars and their legends fit perfectly.

Tinkering with tickers

Introduce x-axis ticks with plt.xticks() to tether data points to their labels - it's like putting addresses on them!

Scatter plots and histograms - the exotic guests

Scatter plots or histograms can be the life of the party, but they need a personal invitation. Use axes methods such as ax.scatter or ax.hist:

fig, ax = plt.subplots() ax.scatter([...], label='Lively dots') ax.hist([...], label='Structured stacks') # Who doesn't love a good introduction? ax.legend() plt.show()

Mathematical performances

For plots that involve math equations, you need a mathematician. numpy is your guy, helping you incorporate constants (numpy.pi) or arrays effortlessly.

Anecdotes and reminders

Simplicity is sophistication

Make your plot speak for itself, without fancy extras. Stick to plt methods, cache axes into variables only when needed, and remember - less means more!

Stay updated

To avail all the latest features, ensure you're hanging out with Python 3.8.0 or later.

Knowledge is power

The official documentation is your personal guide to navigating the realm of legend customization like a pro.

Tackling tricky odds

Overlapping legendaries

Is your legend photobombing the data? Use loc='best' or manual coordinates bbox_to_anchor=(x_pos, y_pos) to get it out of the plot's face.

Legends that update

Need your legend to keep up with dynamic updates? legend.remove() and plt.legend() will keep your legend on its toes.

3D plot legends

For 3D plots with mpl_toolkits.mplot3d, your legend gets a ticked pass to the Axes3D instance - just like 2D axes!