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 rotate Matplotlib annotation to match a line?
To rotate Matplotlib annotation to match a line's angle, you need to calculate the line's slope and convert it to the appropriate rotation angle. This ensures text appears parallel to the plotted line.
Steps to Rotate Annotation
- Create a figure and add subplot using figure() and add_subplot() methods
- Initialize slope (m) and intercept (c) for the line equation
- Generate x and y data points using NumPy
- Calculate rotation angle using arctan() of the slope
- Plot the line and add rotated text annotation
Example
Here's how to rotate annotation to match a line's angle −
import numpy as np
import matplotlib.pyplot as plt
# Set figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create figure and subplot
fig = plt.figure()
ax = fig.add_subplot()
# Line parameters
m = 1 # slope
c = 1 # intercept
# Generate data points
x = np.linspace(-2, 2, 10)
y = m * x + c
# Calculate rotation angle in degrees
theta = np.arctan(m)
rotation_angle = np.degrees(theta)
# Plot the line
line, = ax.plot(x, y, 'b-', linewidth=2)
# Add rotated annotation
ax.text(x=x[2], y=y[2]+0.25, s="y=mx+c",
rotation=rotation_angle, fontsize=15, color='green',
ha='center', va='bottom')
plt.grid(True, alpha=0.3)
plt.show()
# This displays a plot with a diagonal line and text "y=mx+c" # rotated to match the line's angle
Understanding the Rotation Calculation
The key is using np.arctan(slope) to get the angle in radians, then converting to degrees −
import numpy as np
# Example with different slopes
slopes = [0, 0.5, 1, 2, -1]
for slope in slopes:
angle_radians = np.arctan(slope)
angle_degrees = np.degrees(angle_radians)
print(f"Slope: {slope:4.1f} ? Angle: {angle_degrees:6.1f}°")
Slope: 0.0 ? Angle: 0.0° Slope: 0.5 ? Angle: 26.6° Slope: 1.0 ? Angle: 45.0° Slope: 2.0 ? Angle: 63.4° Slope: -1.0 ? Angle: -45.0°
Multiple Annotations Example
You can add multiple rotated annotations along different lines −
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 6))
# Different line equations
lines_data = [
{'slope': 0.5, 'intercept': 1, 'color': 'blue', 'label': 'Line 1'},
{'slope': -0.8, 'intercept': 3, 'color': 'red', 'label': 'Line 2'},
{'slope': 1.5, 'intercept': -1, 'color': 'green', 'label': 'Line 3'}
]
x = np.linspace(-2, 4, 100)
for line_data in lines_data:
m = line_data['slope']
c = line_data['intercept']
y = m * x + c
# Plot line
ax.plot(x, y, color=line_data['color'], linewidth=2)
# Calculate rotation angle
rotation_angle = np.degrees(np.arctan(m))
# Add rotated annotation
ax.text(x[50], y[50] + 0.2, line_data['label'],
rotation=rotation_angle, fontsize=12,
color=line_data['color'], ha='center', va='bottom')
ax.grid(True, alpha=0.3)
ax.set_xlim(-2, 4)
ax.set_ylim(-2, 5)
plt.show()
# Displays multiple lines with labels rotated to match each line's angle
Key Parameters
| Parameter | Description | Example |
|---|---|---|
rotation |
Angle in degrees | np.degrees(np.arctan(slope)) |
ha |
Horizontal alignment | 'center', 'left', 'right' |
va |
Vertical alignment | 'center', 'top', 'bottom' |
Conclusion
Use np.arctan(slope) and np.degrees() to calculate the rotation angle for annotations. This ensures text aligns perfectly with line direction, creating professional-looking plots with properly oriented labels.
Advertisements
