꺾은선그래프: 사용법과 예제
꺾은선그래프: 언제 사용하면 좋을까요?
꺾은선그래프는 시간처럼 의미 있는 순서로 값을 연결하며 결측 위치는 비워 둡니다.
이 페이지의 내용
그리기 전에 시간순으로 정렬하고 빈 구간을 확인합니다. 순서가 없는 범주는 막대나 점으로 표시하는 편이 낫습니다.
실행한 예제 그림은 어떤 모습인가요?
아래는 연결된 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
def make(fixed):
x = np.arange(1,8);y = np.array([2.,3.,np.nan,np.nan,6.,5.,7.])
data_file(["time","response"],zip(x,y));fig,ax = canvas()
valid = np.isfinite(y)
if fixed: ax.plot(x,y,"o-")
else: ax.plot(x[valid],y[valid],"o-")
ax.set(xticks=x,xlabel="Time (h)",ylabel="Response (a.u.)",ylim=(0,9),title="NaN breaks the line at two missing observations" if fixed else "Filtering rows bridges the missing interval")
return fig
TRANSPARENT = False
MULTIPAGE = False
RASTER = False
if __name__ == "__main__":
before = make(False)
after = make(True)
before.savefig(OUT / "before.png")
after.savefig(OUT / "after.png", transparent=TRANSPARENT)
after.savefig(OUT / "after.pdf", transparent=TRANSPARENT,
metadata={"CreationDate":None,"ModDate":None})
if MULTIPAGE:
with PdfPages(OUT / "pages.pdf",metadata={"CreationDate":None,"ModDate":None}) as pdf:
pdf.savefig(before); pdf.savefig(after)
if RASTER:
before.savefig(OUT / "vector.pdf", metadata={"CreationDate":None,"ModDate":None})
# Draw at the screen renderer before checking label and legend bounds.
FigureCanvasAgg(after)
after.canvas.draw()
renderer=after.canvas.get_renderer()
checks={"axes":len(after.axes),"text_outside_canvas":[],
"axes_limits":[{"x":list(ax.get_xlim()),"y":list(ax.get_ylim())} for ax in after.axes]}
for ax in after.axes:
xt=[label for value,label in zip(ax.get_xticks(),ax.get_xticklabels()) if min(ax.get_xlim())<=value<=max(ax.get_xlim())]
yt=[label for value,label in zip(ax.get_yticks(),ax.get_yticklabels()) if min(ax.get_ylim())<=value<=max(ax.get_ylim())]
for txt in [ax.title,ax.xaxis.label,ax.yaxis.label,*xt,*yt,*ax.texts]:
if txt.get_visible() and txt.get_text():
b=txt.get_window_extent(renderer)
if b.x0 < -1 or b.y0 < -1 or b.x1 > after.bbox.width+1 or b.y1 > after.bbox.height+1:
checks["text_outside_canvas"].append(txt.get_text())
for legend in [*after.legends,*(ax.get_legend() for ax in after.axes if ax.get_legend())]:
b=legend.get_window_extent(renderer)
assert b.x0>=0 and b.y0>=0 and b.x1<=after.bbox.width and b.y1<=after.bbox.height
print(json.dumps(checks,allow_nan=False))
plt.close("all")
다음으로 어떤 자세한 답변을 읽으면 되나요?
연결된 답변에서 이 그림에 사용한 설정을 자세히 설명합니다.
자세한 조작 설명은 현재 영어·간체 중국어·일본어로 제공됩니다. 아래 링크는 영어판을 엽니다.
How do I break a Matplotlib line at missing observations?
기술 문서: Matplotlib / NumPy 1
R 기초 배우기

