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 label a patch in matplotlib?
To label a patch in matplotlib, you need to add a label parameter when creating the patch and then use legend() to display it. This is useful for creating annotated plots with geometric shapes.
Basic Patch Labeling
Here's how to create and label a rectangle patch ?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Initialize patch position
x = y = 0.1
# Create figure and axis
fig = plt.figure()
ax = fig.add_subplot(111)
# Add rectangle patch with label
patch = ax.add_patch(patches.Rectangle((x, y), 0.5, 0.5,
alpha=0.5,
facecolor='red',
label='Rectangle'))
# Display legend
plt.legend(loc='upper right')
plt.show()
Multiple Labeled Patches
You can add multiple patches with different labels ?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots(figsize=(8, 6))
# Add rectangle
rect = patches.Rectangle((0.1, 0.1), 0.3, 0.4,
facecolor='red', alpha=0.7,
label='Rectangle')
ax.add_patch(rect)
# Add circle
circle = patches.Circle((0.7, 0.3), 0.15,
facecolor='blue', alpha=0.7,
label='Circle')
ax.add_patch(circle)
# Add polygon
triangle = patches.Polygon([(0.2, 0.7), (0.4, 0.9), (0.6, 0.7)],
facecolor='green', alpha=0.7,
label='Triangle')
ax.add_patch(triangle)
# Set axis limits and legend
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend(loc='upper left')
ax.set_title('Multiple Labeled Patches')
plt.show()
Key Points
Use the
labelparameter when creating patchesCall
plt.legend()orax.legend()to display labelsSet
alphafor transparency to make overlapping patches visibleUse
facecolorto set the fill color of patches
Legend Positioning
You can control legend placement with the loc parameter ?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots(figsize=(8, 6))
# Create patches with labels
patches_list = [
patches.Rectangle((0.1, 0.1), 0.2, 0.3, facecolor='red', label='Area 1'),
patches.Rectangle((0.4, 0.2), 0.2, 0.4, facecolor='blue', label='Area 2'),
patches.Rectangle((0.7, 0.3), 0.2, 0.2, facecolor='green', label='Area 3')
]
for patch in patches_list:
ax.add_patch(patch)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
# Different legend positions
ax.legend(loc='center', bbox_to_anchor=(0.5, -0.1), ncol=3)
ax.set_title('Legend Below Plot')
plt.tight_layout()
plt.show()
Conclusion
Label matplotlib patches by adding a label parameter when creating them and calling legend() to display the labels. This creates clear, annotated visualizations with geometric shapes.
