python两线段之间画弧标注角度
时间: 2025-01-17 09:40:54 浏览: 48
### 使用 Matplotlib 绘制两条线段间的角度弧形标记
为了实现这一目标,可以利用 `matplotlib` 库中的多个功能组合完成。具体来说,可以通过计算两条直线之间的夹角并使用 `Arc` 类来绘制代表该角度大小的圆弧。
对于指定两线段起点相同的情况,先定义这两条线段的方向向量,接着通过反正切函数 (`numpy.arctan2`) 计算各自相对于水平轴的角度值,从而得到两者之间形成的最小正交角度范围。之后,在此范围内创建一个适当半径的小扇区作为角度指示器。
下面给出一段完整的 Python 代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
def draw_angle_marker(ax, line1_start, line1_end, line2_end, radius=1):
"""
在给定的坐标系 ax 中画出由line1和line2形成的角度标记
参数:
ax : AxesSubplot 对象
要在其上绘画的目标图形区域
line1_start, line1_end, line2_end : tuple (x, y)
定义两条射线起始点以及终点位置
radius : float
圆弧半径,默认为单位长度
"""
# 获取各点坐标分量
x0, y0 = line1_start
x1, y1 = line1_end
x2, y2 = line2_end
# 计算方向向量及其对应角度
angle1 = np.degrees(np.arctan2(y1-y0,x1-x0))
angle2 = np.degrees(np.arctan2(y2-y0,x2-x0))
start_angle = min(angle1,angle2)%360
end_angle = max(angle1,angle2)%360
arc_width = abs(end_angle-start_angle)
if arc_width>180:
temp=start_angle;start_angle=end_angle;end_angle=temp
arc_width=-arc_width%360
# 添加圆弧对象至当前图像
arc_patch = Arc((x0,y0),radius*2,radius*2,
theta1=start_angle,theta2=start_angle+arc_width,color='red')
ax.add_patch(arc_patch)
fig, ax = plt.subplots()
ax.set_xlim(-5, 5); ax.set_ylim(-5, 5)
# 创建测试数据集表示两条相交于原点的斜率不同的线段
p1 = (-4,-4); p2=(4,4) # 斜率为正值的第一条线段
q1 = (-4,4); q2=(4,-4) # 斜率为负值的第二条线段
plt.plot([p1[0],p2[0]], [p1[1],p2[1]], marker="o", label="Line Segment A")
plt.plot([q1[0],q2[0]], [q1[1],q2[1]], marker="s", label="Line Segment B")
draw_angle_marker(ax,p1,p2,q2,radius=2)[^1]
plt.legend(); plt.gca().set_aspect('equal'); plt.grid(True)
plt.show()
```
这段程序展示了如何基于已知两点构建一条线段,并且能够正确地在它们所构成的角度内部放置一个小红颜色的圆弧以直观展示二者间的相对方位关系。
阅读全文
相关推荐


















