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
Selected Reading
How to annotate several points with one text in Matplotlib?
Matplotlib provides the annotate() method to add text labels to specific points on a plot. This is useful for highlighting important data points or providing additional context to your visualizations.
Basic Annotation Example
Let's start with a simple example of annotating multiple points on a scatter plot ?
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.figure(figsize=(8, 6))
# Create sample data
x_points = np.array([1, 3, 5, 7, 9])
y_points = np.array([2, 8, 3, 9, 5])
# Create labels for each point
labels = ['Point A', 'Point B', 'Point C', 'Point D', 'Point E']
# Create scatter plot
plt.scatter(x_points, y_points, c='red', s=100)
# Annotate each point
for label, x, y in zip(labels, x_points, y_points):
plt.annotate(label,
xy=(x, y),
xytext=(10, 10),
textcoords='offset points',
ha='left',
fontsize=10,
bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7))
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Annotated Scatter Plot')
plt.grid(True, alpha=0.3)
plt.show()
Advanced Annotation with Arrows
You can add arrows pointing from the text to the data points for better visualization ?
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
# Generate random data
x_points = np.linspace(1, 10, 8)
y_points = np.random.rand(8) * 10
# Create formatted labels
labels = [f"Value: {y:.1f}" for y in y_points]
# Create scatter plot with color mapping
plt.scatter(x_points, y_points, c=x_points, cmap='viridis', s=100)
# Annotate each point with arrows
for label, x, y in zip(labels, x_points, y_points):
plt.annotate(label,
xy=(x, y),
xytext=(20, 20),
textcoords='offset points',
ha='center',
va='bottom',
bbox=dict(boxstyle='round,pad=0.4', facecolor='white', alpha=0.8),
arrowprops=dict(arrowstyle='->',
connectionstyle='arc3,rad=0.1',
color='black'))
plt.xlabel('X Coordinates')
plt.ylabel('Y Coordinates')
plt.title('Scatter Plot with Arrow Annotations')
plt.colorbar(label='Color Scale')
plt.grid(True, alpha=0.3)
plt.show()
Key Parameters
Understanding the important parameters of annotate() method ?
| Parameter | Description | Example Values |
|---|---|---|
xy |
Point being annotated | (x, y) |
xytext |
Position of text |
(10, 20) pixels offset |
textcoords |
Coordinate system for xytext |
'offset points', 'data'
|
ha |
Horizontal alignment |
'left', 'center', 'right'
|
va |
Vertical alignment |
'top', 'center', 'bottom'
|
Styling Annotations
You can customize the appearance of annotations with different styles ?
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
# Create data points
x_data = [1, 2, 3, 4, 5]
y_data = [10, 25, 15, 30, 20]
labels = ['Start', 'Peak 1', 'Valley', 'Peak 2', 'End']
# Plot line with markers
plt.plot(x_data, y_data, 'o-', linewidth=2, markersize=8, color='blue')
# Different annotation styles
styles = [
dict(boxstyle='round,pad=0.3', facecolor='lightblue', alpha=0.8),
dict(boxstyle='square,pad=0.3', facecolor='lightgreen', alpha=0.8),
dict(boxstyle='round,pad=0.3', facecolor='orange', alpha=0.8),
dict(boxstyle='square,pad=0.3', facecolor='pink', alpha=0.8),
dict(boxstyle='round,pad=0.3', facecolor='lightyellow', alpha=0.8)
]
# Apply different styles to each annotation
for i, (label, x, y) in enumerate(zip(labels, x_data, y_data)):
plt.annotate(label,
xy=(x, y),
xytext=(0, 25),
textcoords='offset points',
ha='center',
fontweight='bold',
bbox=styles[i],
arrowprops=dict(arrowstyle='->', color='black'))
plt.xlabel('Time Points')
plt.ylabel('Values')
plt.title('Styled Annotations Example')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Conclusion
Use annotate() to add descriptive text to data points in Matplotlib. Combine with bbox styling and arrowprops for professional-looking annotations that enhance data visualization clarity.
Advertisements
