Manually add legend Items Python Matplotlib

In Matplotlib, you can manually add legend items using the plt.legend() method. This allows you to create custom legends with specific labels, positions, and styling options like borders.

Basic Syntax

plt.legend(labels, loc=location, frameon=True/False)

Parameters

  • labels ? List of strings for legend labels

  • loc ? Location of the legend (0 for best location)

  • frameon ? Boolean to show/hide the legend border

Example

Here's how to create a plot with manually added legend items ?

import matplotlib.pyplot as plt

# Set axis labels
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Plot two lines
plt.plot([1, 2, 3, 4], [1, 4, 2, 3], color='blue')
plt.plot([1, 2, 3, 4], [2, 3, 4, 1], color='orange')

# Manually add legend items
plt.legend(["Blue Line", "Orange Line"], loc=0, frameon=True)

plt.show()

Legend Location Options

Location Code Position
0 Best (automatic)
1 Upper right
2 Upper left
3 Lower left
4 Lower right

Advanced Example

You can customize the legend further with additional parameters ?

import matplotlib.pyplot as plt

plt.xlabel("Time")
plt.ylabel("Value")

# Create multiple plots
plt.plot([1, 2, 3, 4], [1, 4, 2, 3], 'b-', linewidth=2)
plt.plot([1, 2, 3, 4], [2, 3, 4, 1], 'r--', linewidth=2)
plt.plot([1, 2, 3, 4], [3, 1, 3, 2], 'g:', linewidth=2)

# Manual legend with custom styling
plt.legend(['Solid Blue', 'Dashed Red', 'Dotted Green'], 
           loc='upper left', 
           frameon=True,
           shadow=True,
           fancybox=True)

plt.grid(True, alpha=0.3)
plt.show()

Conclusion

Use plt.legend() with a list of labels to manually create legend items. Set frameon=True for borders and use loc parameter to control positioning for better plot readability.

Updated on: 2026-03-25T18:00:36+05:30

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements