0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Add Legend in Matplotlib: Simple Guide

To add a legend in matplotlib, use the plt.legend() function after plotting your data. You can label each plot with the label parameter and then call plt.legend() to display the legend on the graph.
๐Ÿ“

Syntax

The basic syntax to add a legend in matplotlib is:

  • label: Assign a name to each plot element when plotting.
  • plt.legend(): Call this function to show the legend on the plot.
python
plt.plot(x, y, label='Line 1')
plt.legend()
๐Ÿ’ป

Example

This example shows how to plot two lines with labels and add a legend to distinguish them.

python
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()
plt.title('Example of Adding Legend')
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.show()
Output
A plot window showing two lines labeled 'Squares' and 'Primes' with a legend box identifying each line.
โš ๏ธ

Common Pitfalls

Common mistakes when adding legends include:

  • Forgetting to add label to each plot, so the legend has no names.
  • Calling plt.legend() before plotting, which shows an empty legend.
  • Using multiple plots without labels, resulting in no legend entries.

Always assign label when plotting and call plt.legend() after all plots.

python
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [1, 4, 9]

# Wrong: No labels, legend will be empty
plt.plot(x, y)
plt.legend()  # No legend entries

# Right: Add labels
plt.plot(x, y, label='Squares')
plt.legend()
๐Ÿ“Š

Quick Reference

Tips for using legends in matplotlib:

  • Use label='name' in plot functions.
  • Call plt.legend() after all plots.
  • Customize legend location with plt.legend(loc='best').
  • Use plt.legend(title='Legend Title') to add a title.
โœ…

Key Takeaways

Always add the label parameter to each plot to name legend entries.
Call plt.legend() after plotting to display the legend.
Without labels, the legend will be empty or missing entries.
You can customize legend position and appearance with parameters.
Legends help make plots easier to understand by identifying lines or markers.