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 a range of the X-axis in Matplotlib?
Annotating a range of the X-axis in Matplotlib helps highlight specific sections of your data. This is useful for marking important intervals, peaks, or regions of interest in your plots.
Basic Range Annotation
Use annotate() with arrow properties to create a visual range indicator ?
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create data points
xx = np.linspace(0, 10)
yy = np.sin(xx)
fig, ax = plt.subplots(1, 1)
ax.plot(xx, yy)
ax.set_ylim([-2, 2])
# Annotate range with arrow
ax.annotate('', xy=(5, 1.5), xytext=(8, 1.5),
xycoords='data', textcoords='data',
arrowprops={'arrowstyle': '<|-|>', 'color': 'red'})
# Add range label
ax.annotate('Range of Interest', xy=(6.5, 1.7), ha='center', va='center', color='red')
plt.show()
Multiple Range Annotations
You can annotate multiple ranges with different colors and labels ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 10, 100)
y = np.sin(x) * np.exp(-x/10)
fig, ax = plt.subplots(1, 1, figsize=(8, 4))
ax.plot(x, y, 'b-', linewidth=2)
# First range annotation
ax.annotate('', xy=(1, 0.6), xytext=(3, 0.6),
arrowprops={'arrowstyle': '<|-|>', 'color': 'red', 'lw': 2})
ax.annotate('Peak Region', xy=(2, 0.7), ha='center', color='red', fontsize=10)
# Second range annotation
ax.annotate('', xy=(6, -0.4), xytext=(9, -0.4),
arrowprops={'arrowstyle': '<|-|>', 'color': 'green', 'lw': 2})
ax.annotate('Decay Region', xy=(7.5, -0.5), ha='center', color='green', fontsize=10)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.grid(True, alpha=0.3)
plt.show()
Key Parameters
| Parameter | Description | Example Value |
|---|---|---|
xy |
Start point of annotation | (5, 1.5) |
xytext |
End point of annotation | (8, 1.5) |
arrowstyle |
Style of arrow/range indicator | '<|-|>' |
ha |
Horizontal alignment | 'center' |
Conclusion
Use annotate() with arrowstyle='<|-|>' to create range indicators on your X-axis. This technique is perfect for highlighting specific data intervals or marking regions of interest in your matplotlib plots.
Advertisements
