영역 채우기 그림: 사용법과 예제
영역 채우기 그림: 언제 사용하면 좋을까요?
영역 채우기는 곡선과 기준 사이를 강조합니다. 기준선이나 임계값의 의미를 명시합니다.
이 페이지의 내용
곡선이 임계값을 지나는 위치를 확인합니다. 표본점 사이를 채울 때는 교차점 보간이 필요할 수 있습니다.
실행한 예제 그림은 어떤 모습인가요?
아래는 연결된 Bopbun 예제에서 실제 생성한 전체 결과입니다. 입력 데이터와 실행 코드도 함께 제공합니다.
이 글에서는 모의 예제 데이터를 사용합니다.

이 예제는 어떻게 재현하나요?
코드를 쓰기 가능한 폴더에 저장하고 필요한 패키지를 설치한 뒤 python example.py를 실행합니다. 원래 예제의 실행 환경은 Python 3.12.4 · NumPy 1.26.4 · Matplotlib 3.8.4입니다.
아래는 이 글에서 사용한 코드, 데이터, 실행 결과 파일입니다. 코드를 따라 실행하거나 자신의 결과와 비교할 때 사용할 수 있어요.
- example.py컴퓨터에서 실행할 수 있는 전체 예제 코드입니다.
- data.csv예제에 사용한 입력 데이터입니다. 표로 열어 볼 수 있어요.
- after.png이 글의 설정으로 만든 결과 그림입니다.
- after.pdf확인하거나 문서에 배치할 수 있는 PDF 결과 파일입니다.
- 사용 라이선스 · LICENSE.txt코드, 데이터, 그림의 사용 조건과 출처 및 글꼴 라이선스입니다.
전체 소스 코드
# Original Bopbun example, CC0-1.0. See LICENSE.txt for font/software notices.
# Tested: Python 3.12.4, Matplotlib 3.8.4, NumPy 1.26.4.
from pathlib import Path
import csv
import json
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import colors, dates
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib.backends.backend_agg import FigureCanvasAgg
from datetime import datetime, timedelta
from textwrap import fill
OUT = Path(__file__).resolve().parent
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 11,
"axes.spines.top": False, "axes.spines.right": False,
"pdf.fonttype": 42, "figure.dpi": 120, "savefig.dpi": 160})
def data_file(header, rows):
with (OUT / "data.csv").open("w", newline="", encoding="utf-8") as f:
w = csv.writer(f); w.writerow(header); w.writerows(rows)
def canvas():
return plt.subplots(figsize=(7.2, 4.5), layout="constrained")
def line_data():
x = np.arange(1, 7)
y = np.array([2., 4., 3., 6., 5., 8.])
data_file(["time", "response"], zip(x, y))
return x, y
def matrix_data():
z = np.array([[1., 3., 5., 7.], [2., 4., 6., 8.], [0., 2., 4., 6.]])
data_file(["row", "column", "value"], ((i,j,z[i,j]) for i,j in np.ndindex(z.shape)))
return z
from matplotlib import ticker
from matplotlib.collections import LineCollection
def make(fixed):
x=np.arange(7);y=np.array([2,5,4,7,6,3,5]);data_file(['time','response'],zip(x,y));fig,ax=canvas();ax.plot(x,y,'o-')
ax.axhline(4,color='black',linestyle='--',label='Threshold = 4')
if fixed:ax.fill_between(x,4,y,where=y>4,interpolate=True,alpha=0.3,color='#bf6d33')
ax.set(xlabel='Time (h)',ylabel='Response (a.u.)',ylim=(0,9),title='Fill only the part above a threshold');ax.legend();return fig
if __name__ == '__main__':
before=make(False);after=make(True)
before.savefig(OUT/'before.png');after.savefig(OUT/'after.png')
after.savefig(OUT/'after.pdf',metadata={'CreationDate':None,'ModDate':None})
after.canvas.draw();print(json.dumps({'axes':len(after.axes),'limits':[{'x':list(a.get_xlim()),'y':list(a.get_ylim())} for a in after.axes]}))
plt.close('all')
다음으로 어떤 자세한 답변을 읽으면 되나요?
연결된 답변에서 이 그림에 사용한 설정을 자세히 설명합니다.
자세한 조작 설명은 현재 영어·간체 중국어·일본어로 제공됩니다. 아래 링크는 영어판을 엽니다.
How do I shade only the part of a Matplotlib curve above a threshold?
기술 문서: Matplotlib / NumPy 1
R 기초 배우기

