Matplotlib.pyplot.legend() in Python
0 667
Understanding Matplotlib.pyplot.legend() in Python
Legends are an essential part of data visualization, especially when dealing with multiple datasets in the same plot. The matplotlib.pyplot.legend() function helps label each line or shape, making your chart easier to understand at a glance.
Basic Usage of legend()
To use legend(), you first assign a label to each plotted element using the label argument. Then, simply call plt.legend() to display the legend box on your figure.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y1 = [2, 4, 6, 8]
y2 = [1, 2, 3, 4]
plt.plot(x, y1, label='Double')
plt.plot(x, y2, label='Same')
plt.legend()
plt.show()
In this example, both lines are labeled. The legend function automatically displays these labels in a small box on the chart.
Setting the Legend Position
You can control where the legend appears using the loc parameter. Common options include: 'upper left', 'lower right', 'center', etc. Matplotlib also supports loc='best', which automatically selects a location with minimal overlap.
plt.legend(loc='upper left')
If you want to position the legend outside the chart, use the bbox_to_anchor parameter to set custom coordinates.
plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1))
Customizing the Appearance of the Legend
You can personalize the legend to match your visualization style. Options include changing the font size, adding a title, and adjusting spacing or box styling.
plt.legend(
title='Line Types',
fontsize='medium',
title_fontsize='large',
shadow=True,
fancybox=True,
framealpha=0.8
)
These options control how the legend box looks and how easily it blends into your plot.
Using Legends with Multiple Plots
If you have more than one set of data and plots, you can update or combine legends using handles and labels manually. This gives more control over what appears in the final legend.
line1, = plt.plot(x, y1, label='Line A')
line2, = plt.plot(x, y2, label='Line B')
plt.legend(handles=[line1, line2])
This method is useful when some plotted elements shouldn't appear in the legend or when plotting in multiple steps.
Adding Multiple Legends (Advanced)
While not common, adding more than one legend is possible by creating separate legend objects and placing them manually on the figure.
fig, ax = plt.subplots()
line1, = ax.plot(x, y1, label='Group A')
line2, = ax.plot(x, y2, label='Group B')
legend1 = ax.legend(loc='upper left')
ax.add_artist(legend1)
line3, = ax.plot(x, [i*3 for i in y2], label='Group C')
ax.legend(loc='lower right')
This technique helps when working with grouped data or mixed visualizations where multiple legends make sense.
Conclusion
The matplotlib.pyplot.legend() function in Python is a powerful way to make your plots more informative and easier to read. With options to customize positioning, style, and grouping, you can adapt legends to fit any type of visualization effectively.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments