Home » Tutorial on Matplotlib Legends in Python

Tutorial on Matplotlib Legends in Python

Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Oracle Java Certification
Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests

Legends in Matplotlib provide context to a plot by labeling different lines, bars, or other plot elements, helping users understand what each color or symbol represents.

Matplotlib provides highly customizable options for creating, positioning, and styling legends.

In this tutorial, we’ll go through the basics of adding legends, positioning them, and customizing their appearance.

1. Basic Legend

In Matplotlib, the easiest way to add a legend is by using the label argument in the plotting function and then calling plt.legend().

import matplotlib.pyplot as plt

# Create some sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 8, 27, 64, 125]

# Plot the data with labels
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Display the legend
plt.legend()

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Basic Legend Example")
plt.show()

2. Positioning the Legend

The loc parameter in plt.legend() allows you to position the legend in different parts of the plot. Common locations include:

  • ‘upper right' (default)
  • ‘upper left'
  • ‘lower left'
  • ‘lower right'
  • ‘center'
  • ‘best' (automatically positions the legend where it avoids data overlap)
# Plot with different legend positions
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Set the legend position to 'upper left'
plt.legend(loc='upper left')

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Legend Positioned at Upper Left")
plt.show()

3. Customizing Legend Colors and Fonts

You can adjust the color, font size, and font family of the legend text to make it more readable or visually pleasing.

# Plot data with labels
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Customize legend appearance
plt.legend(loc='upper left', fontsize='large', title="Legend", title_fontsize='medium', shadow=True, fancybox=True)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Customized Legend Appearance")
plt.show()

4. Legend Outside the Plot

You can place the legend outside the main plot area by using the bbox_to_anchor parameter.

# Plot data
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Position legend outside plot
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Legend Positioned Outside Plot")
plt.tight_layout()
plt.show()

5. Using Multiple Legends

If you want to create multiple legends, you can use ax.legend() to place legends on specific axes. Note that each legend must be handled individually.

# Create subplots
fig, ax = plt.subplots()

# Plot data
ax.plot(x, y1, label='y = x^2', color='blue')
ax.plot(x, y2, label='y = x^3', color='green')

# Add the first legend
legend1 = ax.legend(loc='upper left', fontsize='small', title="First Legend")

# Add a second legend for the line styles (using proxy artists)
from matplotlib.lines import Line2D

# Proxy legend elements
legend_elements = [Line2D([0], [0], color='blue', lw=2, label='Blue Line'),
                   Line2D([0], [0], color='green', lw=2, label='Green Line')]
legend2 = ax.legend(handles=legend_elements, loc='lower right', title="Colors")

# Add both legends to the plot
ax.add_artist(legend1)
plt.show()

6. Changing Legend Marker Size and Style

To make the legend markers more distinct, you can change their size and style using handlelength, handletextpad, and markerscale.

# Plot with different marker sizes and styles
plt.plot(x, y1, label='y = x^2', marker='o', markersize=10)
plt.plot(x, y2, label='y = x^3', marker='s', markersize=8)

# Customize legend marker size
plt.legend(loc='upper left', markerscale=1.5, handlelength=2, handletextpad=0.5)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Customized Legend Markers")
plt.show()

7. Using Legends with Different Transparency (Alpha)

You can make your legend background semi-transparent using the alpha parameter. This can be helpful when you want the legend not to obscure important data in the plot.

# Plot data
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Add a semi-transparent legend
plt.legend(loc='upper left', fancybox=True, framealpha=0.5)

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Legend with Transparency")
plt.show()

8. Customizing Legend Box and Frame

The legend box and frame can be customized with different line styles and colors.

# Plot data
plt.plot(x, y1, label='y = x^2')
plt.plot(x, y2, label='y = x^3')

# Customize legend box and frame
plt.legend(loc='upper left', frameon=True, shadow=True, fancybox=True, edgecolor='purple', facecolor='lightgrey')

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Legend with Custom Frame and Background")
plt.show()

9. Legend for Subplots (Multiple Axes)

When working with subplots, legends are added individually for each axis. Here’s an example using multiple subplots, each with its own legend.

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))

# Data for subplot 1
ax1.plot(x, y1, label='y = x^2', color='blue')
ax1.legend(loc='upper left', title="First Plot")
ax1.set_title("First Subplot")

# Data for subplot 2
ax2.plot(x, y2, label='y = x^3', color='green')
ax2.legend(loc='upper left', title="Second Plot")
ax2.set_title("Second Subplot")

plt.show()

10. Custom Legends with Proxy Artists

In some cases, you might want a legend that describes aspects of the plot that aren’t directly related to the plotted data. You can create “proxy artists” for the legend in such cases.

# Import Line2D for creating proxy legends
from matplotlib.lines import Line2D

# Plot data
plt.plot(x, y1, label='y = x^2', color='blue')
plt.plot(x, y2, label='y = x^3', color='green')

# Proxy legend elements
legend_elements = [Line2D([0], [0], color='purple', lw=4, label='Proxy Line 1'),
                   Line2D([0], [0], color='orange', lw=4, label='Proxy Line 2')]

# Display custom legend
plt.legend(handles=legend_elements, loc='upper right', title="Custom Proxy Legend")

plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Custom Legend with Proxy Artists")
plt.show()

Summary

This tutorial covered various ways to use legends in Matplotlib, including:

  • Basic legends with labels
  • Positioning and customizing legends
  • Changing marker sizes and styles in legends
  • Using legends with subplots and proxy artists for custom legends

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More