소개
이 튜토리얼에서는 Matplotlib 의 ~.path.Path와 ~.patches.PathPatch를 사용하여 도넛을 만들 것입니다. make_circle() 함수를 사용하여 원을 만들고, 내부 및 외부 하위 경로를 연결하여 도넛을 생성합니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접속하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
필요한 라이브러리 임포트
이 튜토리얼에 필요한 라이브러리를 임포트하는 것으로 시작합니다.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
import matplotlib.path as mpath
헬퍼 함수 정의
경로의 방향을 결정하기 위해 헬퍼 함수 wise()를 정의합니다.
def wise(v):
if v == 1:
return "CCW"
else:
return "CW"
원 생성
make_circle() 함수를 사용하여 원을 생성합니다. 이 함수는 원의 반지름을 입력으로 받아 원의 x 및 y 좌표를 반환합니다.
def make_circle(r):
t = np.arange(0, np.pi * 2.0, 0.01)
t = t.reshape((len(t), 1))
x = r * np.cos(t)
y = r * np.sin(t)
return np.hstack((x, y))
도넛 생성
내부 및 외부 하위 경로를 연결하여 도넛을 생성합니다. 각 정점의 유형 (MOVETO, LINETO 등) 을 지정하기 위해 codes를 사용합니다. 그런 다음 mpath.Path를 사용하여 Path 객체를 생성하고 mpatches.PathPatch를 사용하여 PathPatch 객체를 생성합니다. 마지막으로 ax.add_patch()를 사용하여 PathPatch 객체를 Axes 객체에 추가합니다.
Path = mpath.Path
fig, ax = plt.subplots()
inside_vertices = make_circle(0.5)
outside_vertices = make_circle(1.0)
codes = np.ones(
len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
codes[0] = mpath.Path.MOVETO
for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
## Concatenate the inside and outside subpaths together, changing their
## order as needed
vertices = np.concatenate((outside_vertices[::outside],
inside_vertices[::inside]))
## Shift the path
vertices[:, 0] += i * 2.5
## The codes will be all "LINETO" commands, except for "MOVETO"s at the
## beginning of each subpath
all_codes = np.concatenate((codes, codes))
## Create the Path object
path = mpath.Path(vertices, all_codes)
## Add plot it
patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
ax.add_patch(patch)
ax.annotate(f"Outside {wise(outside)},\nInside {wise(inside)}",
(i * 2.5, -1.5), va="top", ha="center")
ax.set_xlim(-2, 10)
ax.set_ylim(-3, 2)
ax.set_title('Mmm, donuts!')
ax.set_aspect(1.0)
plt.show()
요약
이 튜토리얼에서는 Matplotlib 의 ~.path.Path 및 ~.patches.PathPatch를 사용하여 도넛을 만드는 방법을 배웠습니다. make_circle() 함수를 사용하여 원을 생성하고 내부 및 외부 하위 경로를 함께 연결하여 도넛을 만들었습니다. 또한 각 정점의 유형을 지정하고 mpath.Path를 사용하여 Path 객체를 생성하는 방법도 배웠습니다. 마지막으로 mpatches.PathPatch를 사용하여 PathPatch 객체를 생성하고 ax.add_patch()를 사용하여 Axes 객체에 추가하는 방법을 배웠습니다.
요약
축하합니다! ~.path.Path 및 ~.patches.PathPatch를 사용하여 도넛을 만드는 랩을 완료했습니다. LabEx 에서 더 많은 랩을 연습하여 기술을 향상시킬 수 있습니다.