Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to manually add a legend with a color box on a Matplotlib figure?
Matplotlib is a popular data visualization library in Python known for its flexibility and high-quality visualizations. By following this tutorial, you will learn how to create a legend with a color box on your Matplotlib figure, making your visualizations more informative and visually appealing.
A legend is a key that labels the elements in our plot with different colors, markers, or lines. By adding a legend, we can understand the data being presented and make it easier for the audience to interpret our visualizations.
Syntax
To manually add a legend with a color box on a Matplotlib figure in Python, we can use the following syntax ?
import matplotlib.patches as mpatches import matplotlib.pyplot as plt # Creating legend with color box color_patch = mpatches.Patch(color='red', label='Legend Label') plt.legend(handles=[color_patch])
In the above syntax, the color box is created using the mpatches.Patch function with the color parameter set to 'red'. The resulting color box is added to the legend using the plt.legend function with the handles parameter set to [color_patch]. The color box appears in the legend as a colored rectangle next to the label text.
Example 1: Simple Legend with Color Box
In this example, we create a simple line plot and add a custom legend with a color box ?
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
# Creating plot
plt.plot([1, 2, 3, 4], color='blue')
plt.title('Simple Plot with Custom Legend')
# Creating legend with color box
color_box = mpatches.Patch(color='red', label='Example Legend', linewidth=2, alpha=0.7)
plt.legend(handles=[color_box], loc='upper right', framealpha=0.5, frameon=True)
# Show plot
plt.show()
The output shows a blue line plot with a red color box in the legend ?
A line plot with a red legend box labeled "Example Legend" in the upper right corner.
Example 2: Multiple Color Boxes for Categories
This example demonstrates how to create multiple color boxes to represent different categories in a scatter plot ?
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
# Create sample data
np.random.seed(42)
x = np.random.randn(100)
y = np.random.randn(100)
categories = np.random.choice(['A', 'B'], 100)
# Create scatter plot with different colors for categories
colors = {'A': 'red', 'B': 'blue'}
for category in ['A', 'B']:
mask = categories == category
plt.scatter(x[mask], y[mask], c=colors[category], alpha=0.6)
# Create manual legend with color boxes
patch_a = mpatches.Patch(color='red', label='Category A')
patch_b = mpatches.Patch(color='blue', label='Category B')
plt.legend(handles=[patch_a, patch_b], loc='upper left', framealpha=0.8)
# Set plot title and axis labels
plt.title('Scatter Plot with Custom Legend')
plt.xlabel('X values')
plt.ylabel('Y values')
# Show plot
plt.show()
The output displays a scatter plot with red and blue points, and a legend showing color boxes for each category ?
A scatter plot with red and blue points, featuring a legend with colored boxes for "Category A" and "Category B".
Customization Parameters
The mpatches.Patch function accepts several parameters to customize the appearance of color boxes ?
| Parameter | Description | Example Value |
|---|---|---|
color |
Fill color of the patch | 'red', '#FF5733' |
label |
Text label for the legend | 'Category A' |
alpha |
Transparency level (0-1) | 0.7 |
linewidth |
Border width of the patch | 2 |
edgecolor |
Border color | 'black' |
Key Points
Use mpatches.Patch() to create custom color boxes for legends
The handles parameter in plt.legend() accepts a list of patches
Customize appearance using parameters like alpha, linewidth, and edgecolor
Position the legend using the loc parameter
Conclusion
Adding custom legends with color boxes enhances the readability of Matplotlib visualizations. Use mpatches.Patch() to create colored rectangles that represent different categories or data groups in your plots.
