0
0
Matplotlibdata~5 mins

Legend placement and styling in Matplotlib

Choose your learning style9 modes available
Introduction

A legend helps explain what each color or line means in a chart. Placing and styling it well makes the chart easier to understand.

You have multiple lines or bars in a chart and want to label them.
You want to move the legend to a clear spot so it doesn't cover data.
You want to change the legend's look to match your style or make it readable.
You want to add a title or change the font size of the legend.
You want to place the legend outside the main chart area.
Syntax
Matplotlib
plt.legend(loc='best', title='Legend Title', fontsize='small', frameon=True, shadow=False, fancybox=True)

loc controls where the legend appears (e.g., 'best', 'upper right').

You can style the legend with title, fontsize, and frame options.

Examples
Places the legend in the upper left corner.
Matplotlib
plt.legend(loc='upper left')
Automatically places the legend where it fits best, with a title and larger font.
Matplotlib
plt.legend(loc='best', fontsize='large', title='My Legend')
Places the legend outside the plot on the right side, centered vertically.
Matplotlib
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
Removes the frame, adds a shadow, and rounds the corners of the legend box.
Matplotlib
plt.legend(frameon=False, shadow=True, fancybox=True)
Sample Program

This code plots two lines labeled 'Squares' and 'Primes'. The legend is placed in the upper left with a title, medium font size, a frame with shadow, and rounded corners.

Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]
y2 = [2, 3, 5, 7]

plt.plot(x, y1, label='Squares')
plt.plot(x, y2, label='Primes')

plt.legend(loc='upper left', title='Number Types', fontsize='medium', frameon=True, shadow=True, fancybox=True)
plt.title('Legend Placement and Styling Example')
plt.show()
OutputSuccess
Important Notes

Use loc='best' to let matplotlib choose the best spot automatically.

Use bbox_to_anchor with loc to place the legend outside the plot area.

Styling options like shadow and fancybox improve the legend's look.

Summary

Legends explain what each plot element means.

You can place legends inside or outside the plot using loc and bbox_to_anchor.

Styling options help make legends clear and visually appealing.