Matplotlib에서 두 선 사이의 각도를 시각화하는 가장 효과적인 방법은 Arc(호) 클래스를 활용하는 것입니다. 두 선이 이루는 각도만큼의 각도 호(angle arc)를 그려서 시각적으로 명확하게 표현할 수 있습니다.
구현 단계
figure()메서드로 새 그림을 생성하거나 기존 그림을 활성화하고, 그림 크기와 서브플롯 주변의 여백을 조정합니다.add_subplot()메서드를 사용해 서브플롯 배치의 일부로~.axes.Axes를 그림에 추가합니다.- 2D 선 인스턴스인 l1과 l2를 생성합니다.
- 생성한 선들을 현재 축(current axes)에 추가합니다.
- 각도를 그리기 위해 타원형 호를 반환하는 사용자 정의 함수를 호출합니다. 호의 크기는 두 선의 기울기(slope)를 이용해 계산됩니다.
add_patch()메서드로 아티스트인 arc를 축에 추가합니다.show()메서드로 최종 그림을 화면에 표시합니다.
코드 예제
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"\u00b0")
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
l1 = plt.Line2D([0, 1], [0, 4], linewidth=1, linestyle="-", color="green")
l2 = plt.Line2D([0, 4.5], [0, 3], linewidth=1, linestyle="-", color="red")
ax.add_line(l1)
ax.add_line(l2)
angle = angle_plot(l1, l2, 0.25)
ax.add_patch(angle)
plt.show()핵심 코드 설명
get_xydata()로 각 선의 좌표 데이터를 가져온 뒤, 두 점의 좌표 차이를 이용해 기울기를 계산합니다. 이어서 math.atan()으로 기울기의 역탄젠트 값을 구하고, math.degrees()를 통해 라디안 값을 도(degree) 단위로 변환합니다. 두 각도 중 작은 값은 theta1, 큰 값은 theta2로 지정되며, Arc 객체가 이 범위를 따라 각도 호를 그립니다. 호의 색상을 별도로 지정하지 않으면 첫 번째 선의 색상이 자동으로 적용됩니다.
출력 결과
