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
Best way to plot an angle between two lines in Matplotlib
The best way to plot an angle between two lines in Matplotlib is to use the Arc class to create an angular arc that visually represents the angle between two intersecting lines.
Basic Approach
To plot an angle between two lines, we need to:
- Calculate the slopes of both lines
- Convert slopes to angles using
math.atan() - Create an Arc patch using the calculated angles
- Add the arc to the plot using
add_patch()
Complete Example
Here's a complete implementation that creates two lines and displays the angle between them ?
from matplotlib import pyplot as plt, patches
import math
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def angle_plot(line1, line2, offset=1.0, color=None, origin=(0, 0),
len_x_axis=1, len_y_axis=1):
xy1 = line1.get_xydata()
xy2 = line2.get_xydata()
slope1 = (xy1[1][1] - xy1[0][1]) / float(xy1[1][0] - xy1[0][0])
angle1 = abs(math.degrees(math.atan(slope1)))
slope2 = (xy2[1][1] - xy2[0][1]) / float(xy2[1][0] - xy2[0][0])
angle2 = abs(math.degrees(math.atan(slope2)))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle = theta2 - theta1
if color is None:
color = line1.get_color()
return patches.Arc(origin, len_x_axis * offset, len_y_axis * offset,
0, theta1, theta2, color=color,
label=str(angle) + u"°")
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
l1 = plt.Line2D([0, 1], [0, 4], linewidth=2, linestyle="-", color="green")
l2 = plt.Line2D([0, 4.5], [0, 3], linewidth=2, linestyle="-", color="red")
ax.add_line(l1)
ax.add_line(l2)
angle_arc = angle_plot(l1, l2, 0.25)
ax.add_patch(angle_arc)
ax.set_xlim(-0.5, 5)
ax.set_ylim(-0.5, 4.5)
ax.grid(True, alpha=0.3)
ax.set_aspect('equal')
plt.show()
How It Works
The angle_plot() function performs these key steps:
- Extract coordinates: Gets the start and end points of each line
- Calculate slopes: Uses the rise-over-run formula
-
Convert to angles: Uses
math.atan()and converts to degrees -
Create arc: Uses
patches.Arc()with calculated angles
Key Parameters
| Parameter | Description | Default |
|---|---|---|
offset |
Size of the angle arc | 1.0 |
origin |
Center point of the arc | (0, 0) |
color |
Arc color | Line1 color |
Enhanced Version with Labels
Here's an improved version that adds angle labels and better formatting ?
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import math
def plot_angle_with_label(line1, line2, offset=0.3, origin=(0, 0)):
xy1 = line1.get_xydata()
xy2 = line2.get_xydata()
slope1 = (xy1[1][1] - xy1[0][1]) / float(xy1[1][0] - xy1[0][0])
slope2 = (xy2[1][1] - xy2[0][1]) / float(xy2[1][0] - xy2[0][0])
angle1 = math.degrees(math.atan(slope1))
angle2 = math.degrees(math.atan(slope2))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle_diff = theta2 - theta1
arc = patches.Arc(origin, offset*2, offset*2, 0, theta1, theta2,
color='blue', linewidth=2)
# Calculate label position
mid_angle = math.radians((theta1 + theta2) / 2)
label_x = origin[0] + (offset + 0.1) * math.cos(mid_angle)
label_y = origin[1] + (offset + 0.1) * math.sin(mid_angle)
return arc, (label_x, label_y, f'{angle_diff:.1f}°')
fig, ax = plt.subplots(figsize=(8, 6))
# Create two lines
l1 = plt.Line2D([0, 2], [0, 3], linewidth=2, color="green", label="Line 1")
l2 = plt.Line2D([0, 3], [0, 1], linewidth=2, color="red", label="Line 2")
ax.add_line(l1)
ax.add_line(l2)
# Add angle arc and label
arc, label_info = plot_angle_with_label(l1, l2, offset=0.4)
ax.add_patch(arc)
ax.text(label_info[0], label_info[1], label_info[2], fontsize=12,
ha='center', va='center')
ax.set_xlim(-0.5, 3.5)
ax.set_ylim(-0.5, 3.5)
ax.grid(True, alpha=0.3)
ax.set_aspect('equal')
ax.legend()
ax.set_title('Angle Between Two Lines')
plt.show()
Conclusion
Use patches.Arc() with calculated slopes and angles to visualize the angle between two lines. The key is converting line slopes to degrees and using them as arc parameters for accurate angle representation.
Advertisements
