0
0
Matplotlibdata~5 mins

Legend placement options in Matplotlib

Choose your learning style9 modes available
Introduction

Legends help explain what each part of a chart means. Placing them well makes charts easier to understand.

When you have multiple lines or bars and want to label them clearly.
When the default legend covers important data points.
When you want to place the legend outside the main chart area.
When you want to customize the look and position of the legend for better readability.
Syntax
Matplotlib
plt.legend(loc='best')

loc controls where the legend appears.

You can use string names like 'upper right' or numbers like 1, 2, etc.

Examples
Places the legend in the upper left corner inside the plot.
Matplotlib
plt.legend(loc='upper left')
Places the legend in the lower right corner inside the plot.
Matplotlib
plt.legend(loc='lower right')
Places the legend outside the plot on the right, centered vertically.
Matplotlib
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
Automatically places the legend where it covers the least data.
Matplotlib
plt.legend(loc='best')
Sample Program

This code plots two lines and places the legend in the upper left corner inside the plot area.

Matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [10, 20, 25, 30]
y2 = [15, 18, 22, 27]

plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

plt.legend(loc='upper left')
plt.title('Legend Placement Example')
plt.show()
OutputSuccess
Important Notes

You can use numeric codes for loc: 0='best', 1='upper right', 2='upper left', 3='lower left', 4='lower right', 5='right', 6='center left', 7='center right', 8='lower center', 9='upper center', 10='center'.

Using bbox_to_anchor lets you fine-tune the legend position outside the plot.

Always check that the legend does not cover important data points.

Summary

Legends explain chart elements and should be placed clearly.

Use loc to choose legend position inside or outside the plot.

Try loc='best' for automatic placement or customize with bbox_to_anchor.