Matplotlib patches 모듈을 사용해서 도형 시각화하기
Matplotlib patches 모듈은 사각형, 원, 타원, 다각형, 화살표 같은 도형을 그리는 클래스를 모아 둔 모듈입니다. 데이터 그래프 위에 관심 구역을 표시하거나, 배치 알고리즘의 결과를 그림으로 확인하거나, 간단한 다이어그램을 그릴 때 유용합니다.
기본 사용법
도형 객체를 만든 다음 ax.add_patch()로 Axes에 추가합니다. 도형을 추가해도 축 범위는 자동으로 조정되지 않으므로 직접 정하거나 ax.autoscale_view()를 호출해야 합니다.
import matplotlib.pyplot as plt
from matplotlib import patches
fig, ax = plt.subplots(figsize=(6.4, 3.6))
ax.add_patch(patches.Rectangle((0.5, 0.5), 2, 1.5, facecolor='#cde8ec', edgecolor='#0f7d8c', lw=2))
ax.add_patch(patches.Circle((4.2, 1.3), 0.8, facecolor='#fde68a', edgecolor='#b45309'))
ax.add_patch(patches.Ellipse((6.6, 1.3), 2.2, 1.0, angle=30, facecolor='#fbcfe8', alpha=0.8))
ax.add_patch(patches.Polygon([(8, 0.4), (9.6, 0.6), (9.2, 2.2), (8.2, 1.8)], closed=True, facecolor='#ddd6fe', edgecolor='#6d28d9'))
ax.add_patch(patches.FancyBboxPatch((1, 2.8), 3, 0.9, boxstyle='round,pad=0.1', facecolor='white', edgecolor='0.3'))
ax.text(2.5, 3.25, 'FancyBboxPatch', ha='center', va='center')
ax.set_xlim(0, 10)
ax.set_ylim(0, 4.2)
ax.set_aspect('equal')

주요 Matplotlib patches 클래스
| 클래스 | 주요 인자 | 설명 |
|---|---|---|
Rectangle |
(x, y), width, height, angle |
왼쪽 아래 꼭짓점 기준 사각형 |
Circle |
(x, y), radius |
원 |
Ellipse |
(x, y), width, height, angle |
중심 기준 타원 |
Polygon |
[(x1, y1), ...], closed |
다각형 |
Wedge |
(x, y), r, theta1, theta2 |
부채꼴 |
FancyArrowPatch |
posA, posB, arrowstyle |
화살표 |
FancyBboxPatch |
(x, y), w, h, boxstyle |
모서리 둥근 상자 |
공통으로 facecolor(면 색), edgecolor(테두리 색), linewidth, linestyle, alpha, fill, hatch(빗금 무늬) 같은 속성을 쓸 수 있습니다.
그래프 위에 구역 표시하기
데이터 그래프에서 특정 구간을 강조할 때 Rectangle을 투명하게 겹치면 효과적입니다.
import numpy as np
x = np.linspace(0, 10, 300)
y = np.sin(x) + 0.1 * x
fig, ax = plt.subplots(figsize=(6.4, 3))
ax.plot(x, y)
ax.add_patch(patches.Rectangle((3.5, -1.2), 2.5, 3, facecolor='orange', alpha=0.2, edgecolor='none'))
ax.annotate('focus', xy=(4.75, 1.4), ha='center')

수평이나 수직 구간만 칠한다면 ax.axvspan(3.5, 6, alpha=0.2)도 간단한 대안입니다.
많은 도형을 빠르게 그리기: PatchCollection
도형이 수백, 수천 개라면 하나씩 add_patch()하는 것보다 PatchCollection으로 묶어 한 번에 추가하는 편이 빠릅니다. 값 배열을 넘기면 컬러맵으로 색을 칠할 수도 있습니다.
from matplotlib.collections import PatchCollection
rng = np.random.default_rng(2)
circles = [patches.Circle((rng.uniform(0, 10), rng.uniform(0, 5)), rng.uniform(0.2, 0.6)) for _ in range(60)]
pc = PatchCollection(circles, cmap='viridis', alpha=0.8, edgecolor='white')
pc.set_array(rng.random(60))
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.add_collection(pc)
fig.colorbar(pc, ax=ax)
ax.set_xlim(0, 10)
ax.set_ylim(0, 5)
ax.set_aspect('equal')

도형 속성 바꾸기와 애니메이션
도형 객체는 만든 뒤에도 set_xy(), set_width(), set_facecolor(), set_center() 같은 메서드로 바꿀 수 있습니다. matplotlib.animation.FuncAnimation과 함께 쓰면 상자가 움직이며 배치되는 과정을 애니메이션으로 보여 줄 수 있습니다.
정리
Matplotlib patches는 도형 객체를 만들고 add_patch()로 추가한 뒤 축 범위와 비율을 맞추는 순서로 씁니다. 많은 도형은 PatchCollection으로 묶으세요. 이 모듈로 상자 배치 결과를 그리는 실전 예는 배치와 연결 (1) 빈 공간 찾아서 상자 배치하기에서 볼 수 있습니다.
새로 올라온 글
파이썬 가상환경 완벽 정리: venv와 uv로 프로젝트 관리하는 7단계
프로젝트마다 패키지 버전이 꼬이는 문제를 파이썬 가상환경으로 해결합니다. 표준 venv부터 빠른 도구 uv까지 7단계로 정리했습니다.
Matplotlib 한글 깨짐 해결 방법 5가지: 윈도우, 맥, 리눅스, 코랩까지
그래프의 한글이 네모 상자로 나오는 이유와 해결 방법을 정리했습니다. 윈도우, macOS, 리눅스, 구글 코랩에서 바로 쓰는 설정 코드를 담았습니다.
PyQt5에서 PyQt6로 옮기기: 꼭 알아야 할 변경점 8가지와 코드 수정법
PyQt5로 만든 프로그램을 PyQt6에서 실행하면 생기는 오류를 유형별로 정리하고, 실제로 실행해 본 수정 코드를 함께 소개합니다.