Matplotlib 화살표에 각도 주석 추가하기

Beginner

This tutorial is from open-source community. Access the source code

소개

이 랩에서는 Matplotlib 의 FancyArrowPatch를 사용하여 생성된 괄호 화살표 스타일에 각도 주석을 추가하는 방법을 배우게 됩니다. 각도 주석은 플롯에서 각도의 방향과 크기를 나타내는 데 유용합니다. 이 랩을 마치면 각도 주석이 있는 괄호 화살표 스타일을 만들고 특정 요구 사항에 맞게 사용자 정의할 수 있습니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화할 수 없습니다.

학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 즉시 해결해 드리겠습니다.

필요한 라이브러리 가져오기 및 플롯 설정

먼저, 필요한 라이브러리를 가져오고 플롯을 설정해야 합니다. matplotlib.pyplotnumpy를 사용합니다. 또한 데이터를 플롯할 figure 와 axis 객체를 생성합니다.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import FancyArrowPatch

fig, ax = plt.subplots()
ax.set(xlim=(0, 6), ylim=(-1, 5))
ax.set_title("Orientation of the bracket arrows relative to angleA and angleB")

회전된 수직선의 점을 얻는 함수 정의

원점 좌표, 선 길이 및 각도를 입력으로 받아 지정된 각도로 회전된 수직선 끝의 xy 좌표를 반환하는 함수를 정의합니다.

def get_point_of_rotated_vertical(origin, line_length, degrees):
    """Return xy coordinates of the vertical line end rotated by degrees."""
    rad = np.deg2rad(-degrees)
    return [origin[0] + line_length * np.sin(rad),
            origin[1] + line_length * np.cos(rad)]

각도 주석이 있는 브래킷 화살표 생성

FancyArrowPatch를 사용하여 각도 주석이 있는 세 가지 브래킷 화살표 스타일을 생성합니다. 각 브래킷 화살표는 angleAangleB에 대해 서로 다른 각도 값을 갖습니다. 또한 각도 주석의 위치를 나타내기 위해 수직선을 추가합니다.

style = ']-['
for i, angle in enumerate([-40, 0, 60]):
    y = 2*i
    arrow_centers = ((1, y), (5, y))
    vlines = ((1, y + 0.5), (5, y + 0.5))
    anglesAB = (angle, -angle)
    bracketstyle = f"{style}, angleA={anglesAB[0]}, angleB={anglesAB[1]}"
    bracket = FancyArrowPatch(*arrow_centers, arrowstyle=bracketstyle,
                              mutation_scale=42)
    ax.add_patch(bracket)
    ax.text(3, y + 0.05, bracketstyle, ha="center", va="bottom", fontsize=14)
    ax.vlines([line[0] for line in vlines], [y, y], [line[1] for line in vlines],
              linestyles="--", color="C0")

각도 주석 화살표 및 텍스트 추가

각 브래킷 화살표 스타일에 각도 주석 화살표와 텍스트를 추가합니다. 먼저, angleAangleB에서 그려진 패치의 상단 좌표를 얻습니다. 그런 다음, 주석 화살표의 연결 방향을 정의합니다. 마지막으로, 플롯에 화살표와 주석 텍스트를 추가합니다.

    ## Get the top coordinates for the drawn patches at A and B
    patch_tops = [get_point_of_rotated_vertical(center, 0.5, angle)
                  for center, angle in zip(arrow_centers, anglesAB)]
    ## Define the connection directions for the annotation arrows
    connection_dirs = (1, -1) if angle > 0 else (-1, 1)
    ## Add arrows and annotation text
    arrowstyle = "Simple, tail_width=0.5, head_width=4, head_length=8"
    for vline, dir, patch_top, angle in zip(vlines, connection_dirs,
                                            patch_tops, anglesAB):
        kw = dict(connectionstyle=f"arc3,rad={dir * 0.5}",
                  arrowstyle=arrowstyle, color="C0")
        ax.add_patch(FancyArrowPatch(vline, patch_top, **kw))
        ax.text(vline[0] - dir * 0.15, y + 0.7, f'{angle}°', ha="center",
                va="center")

플롯 표시

plt.show()를 사용하여 플롯을 표시합니다.

plt.show()

요약

이 랩에서는 Matplotlib 에서 FancyArrowPatch를 사용하여 생성된 브래킷 화살표 스타일에 각도 주석을 추가하는 방법을 배웠습니다. 또한 특정 요구 사항에 맞게 브래킷 화살표 스타일을 사용자 정의하는 방법도 배웠습니다. 제공된 단계별 지침과 샘플 코드를 따르면 이제 Matplotlib 플롯에서 각도 주석이 있는 브래킷 화살표 스타일을 만들 수 있습니다.