Matplotlib 경로 효과 튜토리얼

Beginner

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

소개

이 랩에서는 Matplotlib 에서 경로 효과 (path effects) 를 사용하여 플롯에 특수 효과를 추가하는 방법을 배우게 됩니다. 경로 효과를 사용하면 텍스트 및 플롯 요소에 사용자 정의 스트로크 (strokes), 그림자 및 기타 시각 효과를 추가할 수 있습니다.

VM 팁

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

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

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

라이브러리 가져오기 및 데이터 준비

먼저, 필요한 라이브러리를 가져오고 플롯할 데이터를 준비해야 합니다.

import matplotlib.pyplot as plt
import numpy as np

## Prepare data
arr = np.arange(25).reshape((5, 5))

텍스트에 스트로크 효과 추가

withStroke 경로 효과를 사용하여 텍스트에 스트로크 효과를 추가할 수 있습니다. 이 예제에서는 플롯의 텍스트 주석에 스트로크 효과를 추가합니다.

## Create plot and add text annotation with stroke effect
fig, ax = plt.subplots()
ax.imshow(arr)
txt = ax.annotate("test", (1., 1.), (0., 0),
                   arrowprops=dict(arrowstyle="->",
                                   connectionstyle="angle3", lw=2),
                   size=20, ha="center",
                   path_effects=[patheffects.withStroke(linewidth=3,
                                                        foreground="w")])
txt.arrow_patch.set_path_effects([
    patheffects.Stroke(linewidth=5, foreground="w"),
    patheffects.Normal()])

## Add grid with stroke effect
pe = [patheffects.withStroke(linewidth=3,
                             foreground="w")]
ax.grid(True, linestyle="-", path_effects=pe)

plt.show()

등고선에 스트로크 효과 추가

withStroke 경로 효과를 사용하여 등고선과 레이블에 스트로크 효과를 추가할 수도 있습니다.

## Create plot and add contour lines with stroke effect
fig, ax = plt.subplots()
ax.imshow(arr)
cntr = ax.contour(arr, colors="k")

plt.setp(cntr.collections, path_effects=[
    patheffects.withStroke(linewidth=3, foreground="w")])

clbls = ax.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls, path_effects=[
    patheffects.withStroke(linewidth=3, foreground="w")])

plt.show()

범례에 그림자 효과 추가

withSimplePatchShadow 경로 효과를 사용하여 범례에 그림자 효과를 추가할 수 있습니다.

## Create plot and add shadow effect to legend
fig, ax = plt.subplots()
p1, = ax.plot([0, 1], [0, 1])
leg = ax.legend([p1], ["Line 1"], fancybox=True, loc='upper left')
leg.legendPatch.set_path_effects([patheffects.withSimplePatchShadow()])

plt.show()

요약

이 랩에서는 Matplotlib 에서 경로 효과를 사용하여 플롯에 특수 효과를 추가하는 방법을 배웠습니다. 텍스트, 등고선 및 레이블에 스트로크 효과를 추가하는 방법과 범례에 그림자 효과를 추가하는 방법을 배웠습니다. 경로 효과를 사용하면 데이터를 명확하고 간결하게 전달하는 시각적으로 멋진 플롯을 만들 수 있습니다.