시작하기
설치와 첫 그래프
Matplotlib는 파이썬 플로팅의 기반입니다. pyplot은 상태 기반 인터페이스입니다(MATLAB과 유사). 스크립트에서는 그림을 렌더링하려면 항상 plt.show()를 호출하세요. Jupyter 노트북에서는 셀이 끝나면 그림이 자동으로 렌더링됩니다.
# install
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
# a simple line plot
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()pyplot 상태 인터페이스
pyplot 인터페이스는 MATLAB을 닮았습니다. 각 호출은 내부에서 추적되는 '현재' figure/axes에 대해 동작합니다. 빠른 플롯에는 간결하지만 서브플롯이 여러 개이면 혼란스러워질 수 있습니다. 현재 figure/axes 객체에 접근하려면 plt.gcf()/plt.gca()를 사용하세요.
import matplotlib.pyplot as plt
# pyplot tracks the "current" figure and axes
plt.figure() # create a new figure
plt.plot([1, 2, 3], [4, 5, 2])
plt.title("State-based") # applies to the current axes
plt.xlim(0, 4)
plt.ylim(0, 6)
plt.show()
# plt.gcf() -> current figure, plt.gca() -> current axes
print(plt.gca())Figure와 Axes (OO 인터페이스)
객체지향(OO) 인터페이스는 단일 플롯 이상의 모든 작업에 권장되는 방식입니다. Figure(전체 캔버스)와 하나 이상의 Axes(개별 플롯)를 만들고 그 객체들에 메서드를 호출합니다. 서브플롯, 트윈 축, 복잡한 레이아웃으로도 깔끔하게 확장됩니다.
import matplotlib.pyplot as plt
import numpy as np
# object-oriented interface: explicit Figure and Axes objects
fig, ax = plt.subplots() # fig is the canvas, ax is a single Axes
x = np.linspace(0, 5, 50)
ax.plot(x, x**2, label="x^2")
ax.plot(x, x**3, label="x^3")
ax.set_title("OO Interface")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()공통 임포트와 관례
plt는 pyplot의, np는 NumPy의 사실상 표준 별칭입니다. 거의 모든 튜토리얼과 라이브러리가 이를 기대합니다. rcParams는 전역 설정 딕셔너리로, 스크립트 맨 위에서 한 번 설정하면 DPI, 폰트 크기, 그림 크기 등 많은 기본값을 고정할 수 있습니다.
# the universal alias
import matplotlib.pyplot as plt
import numpy as np
# for the OO interface you often see
from matplotlib.figure import Figure
from matplotlib.axes import Axes
# set a global style once
plt.rcParams["figure.dpi"] = 100
plt.rcParams["font.size"] = 11
# inline backend in Jupyter (not needed in scripts)
# %matplotlib inline백엔드와 plt.show()
백엔드가 그림을 렌더링합니다. 인터랙티브 백엔드(TkAgg, Qt5Agg)는 창을 열고, 비인터랙티브 백엔드(Agg)는 파일만 출력합니다. pyplot을 임포트하기 전에 matplotlib.use()를 호출하세요. plt.show()는 스크립트에서 창이 닫힐 때까지 블로킹되며, Jupyter에서는 %matplotlib inline이 그림을 노트북에 삽입합니다.
import matplotlib
# list available backends
print(matplotlib.rcsetup.all_backends)
# force a backend (do this BEFORE importing pyplot)
# matplotlib.use("Agg") # non-interactive, for saving files
# matplotlib.use("TkAgg") # interactive Tk window
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
# plt.show() blocks until the window is closed
plt.savefig("out.png") # saving works without any GUI backend선 그래프 (plot)
기본 선 그래프
plt.plot(x, y)는 (x, y) 점을 순서대로 연결하는 선을 그립니다. 배열을 하나만 전달하면 y로 사용되고 x는 기본값 0..N-1이 됩니다. plt.grid(True)로 격자선을 켤 수 있습니다. 점은 배열 순서대로 연결되므로 부드러운 곡선을 원하면 x를 먼저 정렬하세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.5)
y = x * 2
plt.plot(x, y)
plt.title("y = 2x")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()여러 개의 선
plt.plot() 호출마다 현재 axes에 새 선이 추가되고 색상 사이클이 자동으로 진행됩니다. plt.legend()가 식별할 수 있도록 각 선에 label=을 지정하세요. Matplotlib는 축 범위를 자동으로 처리하며 가장 큰 범위에 맞춰 확장합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.plot(x, np.sin(x) + np.cos(x), label="sin+cos")
plt.legend()
plt.title("Trig Functions")
plt.show()선 스타일과 마커
형식 문자열 'color+marker+linestyle'(예: 'ro--')은 간결하지만 암호 같습니다. 읽기 좋은 코드를 위해 color=, marker=, linestyle= 키워드 인자를 명시적으로 쓰는 편이 좋습니다. 흔한 linestyle: '-' '--' ':' '-.'. 흔한 마커: 'o' 's' '^' 'D' 'v' '+' 'x'.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 20)
# format string: [color][marker][linestyle]
plt.plot(x, x, "r-") # red solid line
plt.plot(x, x*2, "go--") # green circles, dashed
plt.plot(x, x*3, "bs:") # blue squares, dotted
plt.plot(x, x*4, "k^-.") # black triangles, dash-dot
# explicit kwargs (clearer, recommended)
plt.plot(x, x*5, color="purple", marker="D",
linestyle="-.", linewidth=2, markersize=6)색상
Matplotlib는 다양한 색 형식을 받습니다: 이름('red'), hex 문자열('#FF8800'), RGB(A) 튜플, Tableau 이름('tab:blue'), 사이클 참조('C0'..'C9'), 회색조 문자열('0.5'). 'C0'은 현재 스타일의 첫 번째 색을 선택하므로 플롯이 색상 사이클과 일치하게 유지됩니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
plt.plot(x, x, color="red") # named color
plt.plot(x, x+0.2, color="#FF8800") # hex RGB
plt.plot(x, x+0.4, color=(0.1, 0.8, 0.2))# RGB tuple 0-1
plt.plot(x, x+0.6, color="C0") # cycle color 0
plt.plot(x, x+0.8, color="tab:purple") # Tableau palette
# gray shorthand: a string of float in [0,1]
plt.plot(x, x+1.0, color="0.5") # mid gray
plt.show()선 두께, 알파, zorder
linewidth는 선 두께를 조절합니다(기본 1.5). alpha는 투명도를 설정하며 곡선이 겹칠 때 아래 곡선을 보려면 필수입니다. zorder는 쌓이는 순서를 제어하며 값이 클수록 나중에(위에) 그려집니다. 기본 zorder는 선이 2, 패치가 1입니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# alpha = transparency (0 invisible, 1 opaque)
# zorder = draw order; higher draws on top
plt.fill_between(x, np.sin(x), alpha=0.3, zorder=1)
plt.plot(x, np.sin(x), linewidth=2, zorder=2)
plt.plot(x, np.cos(x), linewidth=4, alpha=0.7, zorder=3)
plt.show()Step과 Stairs 플롯
plt.step()은 디지털 신호와 이산 데이터에 유용한 계단 함수를 그립니다. where는 계단이 오르는 위치를 정합니다('pre', 'post', 'mid'). plt.stairs()(3.4+)는 y 값과 별도의 bin 경계를 받는 현대적 등가물로, hist류 데이터와 잘 맞습니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = [1, 3, 2, 4, 3]
# step: like plot but with horizontal/vertical steps
plt.step(x, y, where="post", label="post")
plt.step(x, y + 1, where="mid", label="mid")
plt.step(x, y + 2, where="pre", label="pre")
plt.legend(title="where=")
# stairs (matplotlib 3.4+): step from explicit bin edges
plt.stairs([1, 2, 1], baseline=0)
plt.show()산점도
기본 산점도
plt.scatter(x, y)는 연결선 없이 점을 찍습니다. 수만 개 이상의 점에서는 각 점이 자기 크기와 색을 가질 수 있어야 하므로 plt.plot(x, y, 'o')보다 느립니다. 균일한 스타일로 최대 속도가 필요하면 마커를 붙인 plt.plot을 사용하세요.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
x = rng.random(50)
y = rng.random(50)
plt.scatter(x, y)
plt.title("Basic Scatter")
plt.xlabel("x")
plt.ylabel("y")
plt.axis("equal") # equal aspect ratio
plt.show()마커 크기와 색
s 인자는 마커의 '면적'이며 단위는 points²입니다(반경이 아님). 따라서 s를 4배로 하면 반경은 2배입니다. cmap과 함께 쓰는 c(색) 인자는 숫자 배열을 컬러맵에 매핑합니다. 점이 겹칠 때는 alpha < 1로 밀도가 보이게 하세요.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(1)
n = 50
x = rng.random(n)
y = rng.random(n)
sizes = rng.random(n) * 500 # area in points^2
colors = rng.random(n) # mapped to colormap
plt.scatter(x, y, s=sizes, c=colors, cmap="viridis", alpha=0.6)
plt.colorbar(label="value")
plt.title("Bubble Chart")
plt.show()컬러맵 산점도
c에 1차원 배열을 전달하면 각 점이 컬러맵에 매핑됩니다. plt.colorbar(sc)로 컬러바를 추가합니다(매핑을 알 수 있도록 scatter의 반환값을 전달해야 합니다). vmin/vmax로 컬러맵 범위를 고정하며, 지정하지 않으면 데이터 최솟값/최댓값에 자동 스케일됩니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
y = np.sin(x)
c = x # color by x value
sc = plt.scatter(x, y, c=c, cmap="plasma", vmin=0, vmax=10)
cb = plt.colorbar(sc)
cb.set_label("x position")
plt.title("Colored by x")
plt.show()투명도와 과밀 플롯
점이 많이 겹치면 불투명한 산점도는 밀도를 숨깁니다. alpha를 약 0.05로 낮추고 마커 크기를 줄이면 구조가 드러납니다. 매우 큰 데이터(10만 점 이상)에는 plt.hexbin이나 plt.hist2d가 bin으로 집계해 원시 scatter보다 빠르고 명확합니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(2)
n = 5000
x = rng.normal(0, 1, n)
y = rng.normal(0, 1, n)
# dense scatter: low alpha reveals density
plt.scatter(x, y, s=5, alpha=0.05, c="navy")
plt.title("Density via alpha")
# alternative: hexbin for very large datasets
plt.figure()
plt.hexbin(x, y, gridsize=40, cmap="Blues")
plt.colorbar(label="count")
plt.show()범주형 산점도
Matplotlib에는 내장 strip plot이 없으므로 x축에 수동 지터(jitter)를 준 scatter가 표준 DIY 방식입니다. 발행 품질의 범주형 플롯(box, violin, swarm)은 Matplotlib 위에 만들어지고 plt 스타일과 통합되는 Seaborn을 쓰는 편이 좋습니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(3)
groups = ["A", "B", "C"]
data = [rng.normal(0, 1, 30),
rng.normal(2, 1, 30),
rng.normal(1, 1.5, 30)]
for i, d in enumerate(data):
# add jitter on x so points do not stack on one line
jitter = rng.uniform(-0.1, 0.1, len(d))
plt.scatter(np.full(len(d), i) + jitter, d, label=groups[i])
plt.xticks(range(len(groups)), groups)
plt.legend()
plt.show()막대 그래프
수직 막대 그래프
plt.bar(x, height)는 수직 막대를 그리며, x는 문자열(범주형)일 수 있습니다. 반환된 BarContainer로 개별 막대에 주석을 달거나 색을 다시 입힐 수 있습니다. plt.text() 루프가 각 막대에 레이블을 붙입니다. ha/va('center'/'bottom')와 y 오프셋을 조절해 레이블이 막대 바로 위에 오게 하세요.
import matplotlib.pyplot as plt
categories = ["Apple", "Banana", "Cherry", "Date"]
values = [25, 40, 30, 15]
bars = plt.bar(categories, values, color="tab:blue", edgecolor="black")
# annotate each bar with its value
for bar, v in zip(bars, values):
plt.text(bar.get_x() + bar.get_width()/2, v + 1,
str(v), ha="center", va="bottom")
plt.title("Fruit Sales")
plt.ylabel("units sold")
plt.ylim(0, 50)
plt.show()수평 막대 그래프
plt.barh(y, width)는 수평 막대를 그립니다. 수직 차트에서 겹칠 긴 범주 레이블에 이상적입니다. 사람들이 리스트를 읽듯 첫 항목이 위에 오도록 ax.invert_yaxis()를 호출하세요. width 기본값은 0.8입니다.
import matplotlib.pyplot as plt
items = ["Reading", "Coding", "Sleep", "Exercise"]
hours = [2, 6, 8, 1]
plt.barh(items, hours, color="tab:green")
plt.xlabel("hours per day")
plt.title("Daily Activities")
# invert so the first item appears at the top
plt.gca().invert_yaxis()
plt.show()그룹 막대 그래프
그룹 막대는 x 위치를 막대 너비의 절반만큼 오프셋해 두 개(이상) 시리즈를 나란히 놓습니다. 너비 w일 때 x +/- w/2 패턴으로 나란히 배치됩니다. 계산이 되도록 np.arange로 숫자 x 위치를 만들고, plt.xticks로 레이블을 다시 붙이세요.
import matplotlib.pyplot as plt
import numpy as np
labels = ["Q1", "Q2", "Q3", "Q4"]
a = [20, 35, 30, 35]
b = [25, 32, 34, 20]
x = np.arange(len(labels))
w = 0.35
plt.bar(x - w/2, a, w, label="2023")
plt.bar(x + w/2, b, w, label="2024")
plt.xticks(x, labels)
plt.ylabel("revenue")
plt.legend()
plt.show()누적 막대 그래프
누적 막대는 bottom= 인자를 사용합니다. 각 시리즈는 이전 시리즈가 끝난 지점에서 시작합니다. 시리즈가 셋 이상이면 누적합니다: bottom = [m+w for m, w in zip(men, women)]. 누적 막대는 총합과 구성을 보여 주지만, 위쪽 시리즈는 범주 간 비교가 어려워집니다.
import matplotlib.pyplot as plt
import numpy as np
labels = ["A", "B", "C"]
men = [20, 35, 30]
women = [25, 32, 34]
plt.bar(labels, men, label="Men")
plt.bar(labels, women, bottom=men, label="Women")
plt.legend()
plt.title("Stacked Bars")
plt.show()오차 막대 가 있는 막대
yerr 인자가 수직 오차 막대를 추가하고, capsize가 막대 끝 캡의 길이를 정합니다. 막대 스타일은 error_kw로 지정합니다. 비대칭 오차는 yerr=[lower_errors, upper_errors]로 전달합니다. barh(xerr)와 plt.errorbar에서도 동작합니다.
import matplotlib.pyplot as plt
import numpy as np
labels = ["A", "B", "C"]
means = [20, 35, 30]
errors = [2, 4, 3]
plt.bar(labels, means, yerr=errors, capsize=6,
color="tab:orange", edgecolor="black",
error_kw={"ecolor": "black", "linewidth": 1.5})
plt.title("Bar with Error Bars")
plt.ylabel("mean value")
plt.show()히스토그램
기본 히스토그램
plt.hist(x)는 데이터를 bin으로 나누고 막대를 그립니다. bins는 정수(bin 개수)이거나 명시적 경계의 시퀀스입니다. 기본적으로 개수를 반환하므로 y축은 빈도입니다. 반환값은 (counts, bin_edges, patches)이며 추가 커스터마이징에 쓸 수 있습니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
data = rng.normal(0, 1, 1000)
plt.hist(data, bins=30)
plt.title("Histogram")
plt.xlabel("value")
plt.ylabel("frequency")
plt.show()bin 개수 정하기
bin 선택은 히스토그램 모습을 크게 바꿉니다. 'auto'는 Sturges와 Freedman-Diaconis 규칙의 최댓값을 씁니다. 합리적인 기본값입니다. 데이터셋 간 비교 가능한 bin을 위해 명시적 경계 배열로 완전히 제어할 수 있습니다. bin이 너무 적으면 구조가 숨겨지고, 너무 많으면 노이즈가 생깁니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(1)
data = rng.normal(0, 1, 1000)
# auto bin selection (Freedman-Diaconis, Sturges, etc.)
plt.hist(data, bins="auto", alpha=0.5, label="auto")
plt.hist(data, bins=10, alpha=0.5, label="10 bins")
plt.hist(data, bins=np.arange(-4, 4, 0.25),
alpha=0.5, label="0.25 width")
plt.legend()
plt.show()여러 개의 히스토그램
겹치는 히스토그램은 두 분포를 모두 보려면 alpha < 1이 필요하며 서로 다른 색을 쓰세요. 세 그룹 이상에서는 stacked=True가 어수러함을 피하지만 비교는 어려워집니다. 히스토그램보다 매끄럽게 겹치는 밀도 곡선은 kdeplot(Seaborn)을 고려하세요.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(2)
a = rng.normal(0, 1, 1000)
b = rng.normal(1, 1.2, 1000)
plt.hist(a, bins=30, alpha=0.6, label="A", color="tab:blue")
plt.hist(b, bins=30, alpha=0.6, label="B", color="tab:orange")
plt.legend()
plt.show()
# stacked alternative
plt.figure()
plt.hist([a, b], bins=30, stacked=True, label=["A", "B"])
plt.legend()
plt.show()밀도 / 정규화
density=True는 개수를 (총합 * bin 너비)로 나누어 막대 면적의 합이 1이 되는 확률 밀도를 만듭니다. 샘플 크기가 다른 히스토그램을 비교할 수 있고 이론적 PDF를 겹쳐 그릴 수 있습니다. 개별 샘플에 가중치는 weights=로 줍니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(3)
data = rng.normal(0, 1, 1000)
# density=True normalizes the area to 1 (PDF)
plt.hist(data, bins=30, density=True, alpha=0.6)
# overlay the theoretical PDF
from scipy.stats import norm
xs = np.linspace(-4, 4, 200)
plt.plot(xs, norm.pdf(xs), "r-", lw=2)
plt.title("Normalized Histogram + PDF")
plt.show()2D 히스토그램
plt.hist2d는 두 변수를 2차원 격자로 bin하고 각 셀을 개수로 색칠합니다. 밀집 데이터용 scatter의 이산 버전입니다. 더 부드러운 출력은 plt.hexbin(육각 bin)을 쓰세요. 둘 다 cmap을 받고 colorbar에 넘길 수 있는 값을 반환합니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(4)
x = rng.normal(0, 1, 10000)
y = x + rng.normal(0, 1, 10000)
plt.hist2d(x, y, bins=40, cmap="Blues")
plt.colorbar(label="count")
plt.title("2D Histogram")
plt.xlabel("x")
plt.ylabel("y")
plt.show()파이 차트
기본 파이 차트
plt.pie(x, labels)는 x의 값으로 파이를 그립니다. autopct는 백분율 레이블 형식을 지정합니다(printf 스타일 문자열 또는 함수). startangle은 첫 웨지의 시작 각도를 회전합니다. 파이가 타원이 아닌 진짜 원이 되도록 항상 plt.axis('equal')을 쓰세요.
import matplotlib.pyplot as plt
labels = ["Rent", "Food", "Transport", "Fun"]
sizes = [1200, 600, 300, 400]
plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=90)
plt.title("Monthly Budget")
plt.axis("equal") # circle, not ellipse
plt.show()Explode와 그림자
explode는 sizes와 같은 길이의 튜플이며, 각 값은 해당 웨지를 중심에서 바깥으로 밀어냅니다(0 = 밀지 않음). shadow=True는 깊이를 위한 드롭 섀도를 추가합니다. explode는 한 조각을 강조할 때 아껴 쓰세요. 모든 웨지를 밀어 내면 어수러해 보입니다.
import matplotlib.pyplot as plt
labels = ["A", "B", "C", "D"]
sizes = [30, 25, 25, 20]
explode = (0, 0.1, 0, 0) # pull the 2nd wedge out
plt.pie(sizes, labels=labels, explode=explode,
shadow=True, autopct="%1.0f%%",
startangle=140)
plt.title("Exploded Pie")
plt.show()도넛 차트
도넛은 구멍이 뚫린 파이입니다. wedgeprops={'width': 0.4}로 전체 웨지 대신 링을 그립니다. plt.text(0, 0, ...)로 중앙 구멍에 요약 레이블을 넣을 수 있습니다. 도넛은 링 길이가 웨지 각도보다 값을 잘 인코딩해서 일반적으로 파이보다 읽기 쉽습니다.
import matplotlib.pyplot as plt
labels = ["A", "B", "C"]
sizes = [40, 35, 25]
wedges, texts = plt.pie(sizes, labels=labels,
wedgeprops=dict(width=0.4, edgecolor="w"))
plt.title("Donut Chart")
# add center text
plt.text(0, 0, "Total\n100", ha="center", va="center", fontsize=14)
plt.show()백분율과 시작 각도
autopct는 백분율을 받아 문자열을 반환하는 함수가 될 수 있어 백분율과 절대 개수를 함께 보여 줄 수 있습니다. startangle + counterclock=False가 웨지 방향을 제어합니다(위에서 시작해 시계 방향. 전통적 읽기 순서). pctdistance가 백분율 레이블 위치를 정합니다.
import matplotlib.pyplot as plt
labels = ["North", "South", "East", "West"]
sizes = [32, 24, 28, 16]
colors = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"]
plt.pie(sizes, labels=labels, colors=colors,
autopct=lambda p: f"{p:.1f}%\n({p*sum(sizes)/100:.0f})",
startangle=90, counterclock=False,
pctdistance=0.75)
plt.show()중첩 파이 (동심원)
radius와 width가 다른 plt.pie를 두 번 호출하면 동심원 링, 즉 간단한 '선버스트'가 됩니다. 바깥 링은 보통 상위 카테고리를, 안쪽 링은 그 세부 항목을 보여 줍니다. 안쪽 반지름을 작게 하고 edgecolor='w'를 더해 웨지를 시각적으로 분리하세요.
import matplotlib.pyplot as plt
# outer ring: regions, inner ring: sub-categories
outer = [40, 30, 30]
inner = [20, 20, 15, 15, 25, 5]
outer_labels = ["A", "B", "C"]
inner_labels = ["A1", "A2", "B1", "B2", "C1", "C2"]
plt.pie(outer, labels=outer_labels, radius=1.0,
wedgeprops=dict(width=0.3, edgecolor="w"))
plt.pie(inner, labels=inner_labels, radius=0.7,
wedgeprops=dict(width=0.3, edgecolor="w"))
plt.title("Nested Pie")
plt.show()서브플롯과 레이아웃
plt.subplot
plt.subplot(rows, cols, index)는 격자에서 (1부터 시작하는) axes를 선택합니다. 레거시 MATLAB 스타일 방식입니다. 인덱스는 왼쪽→오른쪽, 위→아래로 진행됩니다. '현재 axes'를 바꾸므로 이후 plt 호출이 거기에 그립니다. 새 코드에는 plt.subplots()가 더 깔끔하고 실제 Axes 객체를 반환하므로 권장됩니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 50)
# subplot(nrows, ncols, index) -- 1-indexed!
plt.subplot(2, 2, 1)
plt.plot(x, x)
plt.subplot(2, 2, 2)
plt.plot(x, x**2)
plt.subplot(2, 2, 3)
plt.plot(x, x**3)
plt.subplot(2, 2, 4)
plt.plot(x, np.sin(x))
plt.tight_layout()
plt.show()plt.subplots
plt.subplots(nrows, ncols)는 (fig, axes)를 반환하며 axes는 Axes의 NumPy 배열입니다. axes[row, col]처럼 인덱싱하세요. sharex/sharey는 눈금을 맞추고 공간을 절약합니다. fig.suptitle()은 모든 서브플롯 위의 figure 수준 제목을 지정합니다. 레이블 겹침을 피하려면 항상 plt.tight_layout()을 쓰세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
# one figure, 2x2 grid of Axes, shared x and y
fig, axes = plt.subplots(2, 2, figsize=(8, 6),
sharex=True, sharey=True)
axes[0, 0].plot(x, np.sin(x)); axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x)); axes[0, 1].set_title("cos")
axes[1, 0].plot(x, np.tan(x)); axes[1, 0].set_title("tan")
axes[1, 1].plot(x, -np.sin(x)); axes[1, 1].set_title("-sin")
fig.suptitle("Trig Family")
plt.tight_layout()
plt.show()GridSpec
GridSpec은 서브플롯 크기를 완전히 제어합니다. 슬라이싱으로 셀을 병합할 수 있습니다(gs[0, :] = 한 행 전체, gs[1:, 2] = 오른쪽 세로 열). width_ratios/height_ratios로 크기가 다른 열/행을 만듭니다. 복잡한 대시보드의 표준 도구입니다.
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # full top row
ax2 = fig.add_subplot(gs[1, :2]) # middle, left 2 cols
ax3 = fig.add_subplot(gs[1:, 2]) # right, spans 2 rows
ax4 = fig.add_subplot(gs[2, 0:2]) # bottom-left
ax1.set_title("wide top")
ax3.set_title("tall right")
plt.tight_layout()
plt.show()축 공유
sharex=True(또는 sharey=True)는 축을 연결해 하나를 이동/확대하면 나머지도 갱신됩니다. 쌓인 시계열에 좋습니다. 안쪽 축의 중복 눈금 레이블도 숨깁니다. 공유 그룹은 ax.get_shared_x_axes()로 접근할 수 있고, 그룹에서 축을 제거해 분리할 수도 있습니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(x, np.sin(x))
ax2.plot(x, np.cos(x))
# zooming on one now zooms both
ax1.set_xlim(0, 5)
# decouple later if needed
# ax2.get_shared_x_axes().remove(ax2)
fig.suptitle("Shared x-axis")
plt.show()Tight Layout과 Constrained
tight_layout()은 레이블 겹침을 막기 위해 간격을 한 번 조정하지만 fig.suptitle을 모르므로 rect로 공간을 확보하세요. layout='constrained'(또는 fig=Figure(layout='constrained'))는 그릴 때마다 다시 계산하고 suptitle과 컬러바를 올바르게 처리하는 현대적 대안으로 새 코드에 권장됩니다.
import matplotlib.pyplot as plt
# tight_layout: simple, adjusts subplot spacing
fig, axes = plt.subplots(2, 2)
for ax in axes.flat:
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_title("a title")
fig.suptitle("tight_layout")
plt.tight_layout()
# leave room for suptitle
plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()
# constrained_layout: recomputes on every draw (more robust)
fig, axes = plt.subplots(2, 2, layout="constrained")
fig.suptitle("constrained_layout")
plt.show()범례와 주석
기본 범례
plt.legend()는 그려진 각 아티스트의 label을 모읍니다. loc은 축 안 위치를 정합니다('upper right', 'lower left', 'best', ...). 외부 범례는 bbox_to_anchor=(x, y)(axes 분수 좌표)와 loc을 조합해 범례 박스의 해당 모서리를 그 점에 고정합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.plot(x, x**3, label="cubic")
plt.legend()
plt.show()
# legend outside the axes
plt.figure()
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.legend(loc="upper left", bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.show()범례 위치와 열
ncol은 범례 항목을 여러 열로 배치합니다. 짧은 레이블이 많을 때 유용합니다. frameon/framealpha/fancybox가 범례 박스 모양을 제어하고, title은 제목을 더합니다. 테두리 없는 모양은 frameon=False이며 발행물에서 더 깔끔해 보이는 경우가 많습니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
for i in range(1, 6):
plt.plot(x, x**i, label=f"x^{i}")
plt.legend(loc="upper center", ncol=3, fontsize=9,
frameon=True, framealpha=0.9,
title="Powers", title_fontsize=10)
plt.title("Custom Legend")
plt.show()점 주석 달기
ax.annotate(text, xy, xytext)는 xytext에 텍스트를 놓고 (선택적으로) xy로 화살표를 그립니다. xy는 기본적으로 데이터 좌표입니다. arrowprops는 화살표 스타일 딕셔너리이며 arrowstyle='->'가 가장 흔합니다. 콜아웃에는 plt.text보다 annotate가 훨씬 유연합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
# mark and label the maximum
idx = np.argmax(y)
plt.annotate(f"max = {y[idx]:.2f}",
xy=(x[idx], y[idx]), # point to annotate
xytext=(x[idx]-1, 0.5), # text position
arrowprops=dict(arrowstyle="->"))
plt.show()화살표가 있는 주석
arrowprops는 연결선을 스타일링합니다: arrowstyle ('->', '-|>', '<->'), color, lw. connectionstyle은 화살표를 휘게 합니다. 'arc3,rad=0.3'은 곡선으로, 'angle3'는 직각 꺾임, 'bar'는 T바를 만듭니다. 이를 조합하면 곡선과 겹치지 않고 데이터를 우회하는 명확한 콜아웃을 만들 수 있습니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
plt.plot(x, x**3 - 3*x)
plt.annotate("local min", xy=(1, -2), xytext=(2, -10),
arrowprops=dict(arrowstyle="->", color="red",
lw=2, connectionstyle="arc3,rad=0.3"))
plt.annotate("local max", xy=(-1, 2), xytext=(-3, 8),
arrowprops=dict(arrowstyle="-|>", color="blue",
connectionstyle="angle3"))
plt.show()커스텀 범례 핸들
기본 범례(그려진 아티스트로 구성)가 원하는 것이 아니면 Line2D, Patch 또는 데이터 없는 Line2D로 자체 핸들을 만들어 legend()에 handles=로 전달하세요. 선, 패치, scatter 마커를 하나의 범례에 합칠 때 필수적입니다.
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
plt.plot([1, 2, 3], [1, 4, 9], "o-", color="tab:blue")
plt.plot([1, 2, 3], [1, 8, 27], "s--", color="tab:orange")
custom = [
Line2D([0], [0], color="tab:blue", marker="o", label="squared"),
Line2D([0], [0], color="tab:orange", marker="s", ls="--", label="cubed"),
Patch(facecolor="gray", label="reference band"),
]
plt.legend(handles=custom)
plt.show()스타일, 색상, rcParams
내장 스타일
plt.style.use(name)은 전역으로 프리셋 모양을 적용하고, plt.style.context(name)는 with 블록 안에서 임시로 적용합니다. 인기 있는 스타일: 'ggplot', 'seaborn-v0_8-*', 'bmh', 'fivethirtyeight'. Seaborn 스타일은 Matplotlib 3.6+에서 '-v0_8' 접미사로 이름이 바뀌었음에 유의하세요.
import matplotlib.pyplot as plt
# list all available styles
print(plt.style.available)
# use a style globally
plt.style.use("seaborn-v0_8-whitegrid")
# or as a context manager (temporary)
with plt.style.context("dark_background"):
plt.figure()
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("dark")
plt.show()
plt.plot([1, 2, 3], [9, 4, 1])
plt.title("default again")
plt.show()컬러맵
컬러맵은 세 계열입니다. sequential(viridis, plasma)은 0..N 순서 데이터용, diverging(coolwarm, RdBu)은 의미 있는 중간점이 있는 데이터용(vmin/vmax를 0 중심으로), qualitative(Set2, tab10)은 구분되는 범주용입니다. viridis 같은 지각적으로 균일한 맵을 권장합니다. 색약에 안전하고 인쇄에서도 명확합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
# sequential, diverging, qualitative
for cmap in ["viridis", "plasma", "coolwarm", "RdBu", "Set2"]:
plt.scatter(x, y, c=x, cmap=cmap, label=cmap)
plt.colorbar(label=cmap)
plt.title(cmap)
plt.show()커스텀 색상 사이클
axes.prop_cycle(cycler 객체)은 선을 추가할 때 순환할 속성 시퀀스를 정의합니다. color, linestyle, marker 등을 순환할 수 있으며 cycler(color=[...]) + cycler(linestyle=[...]) 조합으로 동시에 진행됩니다. 모든 플롯에 일관된 브랜드 팔레트를 부여합니다.
import matplotlib.pyplot as plt
from cycler import cycler
# set the default color cycle for new axes
plt.rcParams["axes.prop_cycle"] = cycler(
color=["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00"])
for i in range(1, 6):
plt.plot([0, 1, 2], [i]*3, label=f"line {i}", lw=4)
plt.legend()
plt.title("Custom Cycle")
plt.show()rcParams
rcParams는 모든 기본값을 제어하는 마스터 설정 딕셔너리입니다. 그림 크기, DPI, 폰트, 선 두께, 격자, savefig 옵션 등. 일관된 출력을 위해 스크립트 맨 위에서 한 번 설정하세요. plt.rcParams.update({...})로 여러 값을 동시에 지정합니다. 기본값을 영구 적용하려면 mpl.rcParamsFile 또는 matplotlibrc 파일을 사용합니다.
import matplotlib.pyplot as plt
import matplotlib as mpl
# read / set individual parameters
mpl.rcParams["figure.figsize"] = (8, 4)
mpl.rcParams["figure.dpi"] = 100
mpl.rcParams["font.size"] = 12
mpl.rcParams["axes.grid"] = True
mpl.rcParams["axes.grid.which"] = "both"
mpl.rcParams["savefig.bbox"] = "tight"
# update many at once
plt.rcParams.update({
"axes.titlesize": "large",
"axes.labelsize": "medium",
"lines.linewidth": 2,
})
plt.plot([1, 2, 3])
plt.title("Configured Defaults")
plt.show()색 형식
matplotlib.colors는 변환(to_hex, to_rgb), 이름 있는 색 목록, 컬러맵 구성을 제공합니다. LinearSegmentedColormap.from_list는 소수의 앵커 색으로 연속 컬러맵을 만듭니다. 범주형 커스텀 맵은 ListedColormap(['#aaa', '#bbb', ...])을 쓰세요. 브랜드 팔레트를 정확히 맞출 수 있습니다.
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
# all named colors
print(list(mcolors.CSS4_COLORS)[:5])
# convert between formats
print(mcolors.to_hex((0.1, 0.2, 0.5))) # #1a3380
print(mcolors.to_rgb("#ff8800")) # (1.0, 0.533, 0.0)
# make a custom colormap from a list of colors
cmap = mcolors.LinearSegmentedColormap.from_list(
"rg", ["red", "yellow", "green"])
import numpy as np
plt.imshow(np.linspace(0, 1, 256).reshape(1, -1),
cmap=cmap, aspect="auto")
plt.title("Custom Colormap")
plt.show()축 설정
범위 (xlim / ylim)
plt.xlim/plt.ylim(또는 ax.set_xlim/ax.set_ylim)은 표시되는 데이터 범위를 설정합니다. None을 전달하면 해당 한계는 자동 스케일에 맡기며, 예: set_ylim(None, 5)는 위쪽만 고정합니다. plt.margins()는 고정 한계 대신 데이터 범위의 비율로 여백을 더합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
# set explicit limits
plt.xlim(2, 8)
plt.ylim(-1.5, 1.5)
# or autoscale with margin
# plt.margins(x=0.05, y=0.1)
# query current limits
print(plt.xlim()) # (2.0, 8.0)
plt.show()눈금
plt.xticks(positions)는 눈금 위치를, plt.xticks(positions, labels)는 위치와 텍스트를 설정합니다. 빈 리스트를 전달하면 눈금이 완전히 숨겨집니다. 숫자 축은 보통 MaxNLocator가 자동으로 눈금을 고르게 하고, 범주형 또는 기호적 축(파이의 배수 등)에서만 직접 지정합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
# set tick positions
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
# set positions AND labels
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
["0", "pi/2", "pi", "3pi/2", "2pi"])
# turn off ticks
# plt.xticks([])
plt.show()눈금 서식
ticker 모듈이 정밀 제어를 제공합니다. Locator는 눈금의 '위치'를 결정합니다(MultipleLocator는 N 단위마다, MaxNLocator는 최대 N개, LogLocator는 로그 축용). Formatter는 '레이블' 텍스트를 결정합니다(FormatStrFormatter는 printf 스타일, FuncFormatter는 임의 함수). 보조 격자선에는 minor locator를 사용하세요.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatter
x = np.linspace(0, 5, 100)
plt.plot(x, x**2)
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(MultipleLocator(0.25))
ax.yaxis.set_major_formatter(FormatStrFormatter("%.0f"))
# format with a function
ax.yaxis.set_major_formatter(
FuncFormatter(lambda v, p: f"{v/1000:.1f}k"))
plt.show()로그 스케일
plt.xscale('log') / plt.yscale('log')는 축을 로그 스케일로 바꿉니다. 자릿수가 크게 다른 데이터에 필수입니다. 'symlog'는 0 근처에 선형 구간이 있는 로그 스케일이라 음수도 표시할 수 있습니다. 주 눈금과 보조(로그 간격) 격자선을 모두 보려면 plt.grid(True, which='both')를 쓰세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.logspace(0, 4, 50) # 10^0 .. 10^4
plt.plot(x, x**2)
# log both axes
plt.xscale("log")
plt.yscale("log")
# symlog: log scale that handles negative/zero values
# plt.yscale("symlog", linthresh=1)
plt.title("Log-Log Plot")
plt.grid(True, which="both", ls="--", alpha=0.5)
plt.show()종횡비와 Spines
ax.set_aspect('equal')은 축척이 같아 원이 원으로 유지됩니다. 기하학과 지도에서 중요합니다. Spines는 축 테두리 선이며 위/오른쪽을 숨기는 'despine'은 Seaborn이 유행시킨 더 깔끔한 현대적 모양입니다. spines를 임의 데이터 위치로 옮겨 십자 축을 만들 수도 있습니다.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
theta = np.linspace(0, 2*np.pi, 100)
ax.plot(np.cos(theta), np.sin(theta))
# equal data units on x and y (a true circle)
ax.set_aspect("equal")
# hide the top and right spines
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# move the remaining spines to the center for a cross-hair
# ax.spines["left"].set_position(("data", 0))
# ax.spines["bottom"].set_position(("data", 0))
plt.show()텍스트와 수학 표현식
축 안의 텍스트
ax.text(x, y, s)는 기본적으로 데이터 좌표 에 텍스트를 놓습니다. transform=ax.transAxes를 전달하면 axes 분수 좌표(0,0 = 왼쪽 아래, 1,1 = 오른쪽 위)를 써서 데이터 범위와 무관하게 레이블을 구석에 고정할 수 있습니다. ha/va가 수평/수직 정렬을 제어합니다.
import matplotlib.pyplot as plt
plt.plot([0, 1], [0, 1])
# ax.text(x, y, s) -- x, y in data coords
plt.text(0.5, 0.5, "center of plot", ha="center", va="center",
fontsize=14, color="red", rotation=30)
# align to axes fraction instead of data coords
plt.text(0.02, 0.98, "top-left", transform=plt.gca().transAxes,
ha="left", va="top", bbox=dict(boxstyle="round", fc="yellow"))
plt.show()suptitle과 figtext
fig.suptitle()은 전체 figure에 걸친 제목을 더합니다(모든 서브플롯 위). tight_layout(rect=[...])로 공간을 확보하거나 layout='constrained'를 쓰세요. fig.text(x, y, s)는 figure 분수 좌표(0,0 = figure의 왼쪽 아래)에 텍스트를 놓아 푸터와 출처 메모에 유용합니다.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2)
axes[0].plot([1, 2, 3])
axes[1].plot([3, 2, 1])
# figure-level title (above all axes)
fig.suptitle("Main Title", fontsize=16, fontweight="bold")
# arbitrary figure-coordinate text
fig.text(0.5, 0.01, "figure footer text", ha="center", fontsize=9)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()LaTeX 수학 (mathtext)
Matplotlib에는 내장 mathtext 엔진이 있습니다. LaTeX 비슷한 수학을 달러 기호로 감싸고($...$) raw 문자열(r"...")을 사용하세요. 흔한 명령이 동작합니다: \frac, \sum, \int, 그리스 문자 \alpha..\omega, 위첨자 x^2, 아래첨자 x_i. 외부 LaTeX 설치가 필요 없습니다. 백슬래시를 살리려면 r-문자열을 쓰세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
# mathtext: enclose LaTeX in dollar signs
plt.title(r"$\sin(x)$ vs $x$")
plt.xlabel(r"$x$ (radians)")
plt.ylabel(r"$\sin(x)$")
# fractions, sums, greek letters
plt.text(2, 0.5, r"$\frac{a}{b} + \sum_{i=1}^{n} x_i^2$")
plt.text(2, -0.5, r"$\alpha, \beta, \gamma, \pi, \infty$")
plt.show()텍스트 속성
모든 텍스트 객체는 풍부한 속성을 받습니다. fontsize, fontweight('bold'), fontstyle('italic'), family('serif'/'sans-serif'/'monospace'), color, 배경 박스용 bbox 딕셔너리. 텍스트 객체가 반환되므로 나중에 변경할 수 있습니다(애니메이션과 인터랙티브 갱신에 유용).
import matplotlib.pyplot as plt
t = plt.text(0.5, 0.5, "Styled Text",
fontsize=18, fontweight="bold",
fontstyle="italic", family="serif",
color="darkblue",
bbox=dict(boxstyle="round,pad=0.5",
facecolor="lightyellow", edgecolor="black"))
# animate or update properties later
t.set_fontsize(24)
t.set_color("crimson")
plt.show()주석 (textcoords)
annotate의 textcoords는 xytext 해석 방식을 제어합니다. 'data'(기본, 데이터 단위), 'offset points'(xy 기준 points 오프셋, 점에서 레이블을 살짝 뗄 때 좋음), 'axes fraction'(축 전체 0~1), 'figure fraction'. 좌표계를 섞으면 확대해도 콜아웃이 읽힙니다.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
# xy in data coords, xytext in points OFFSET from xy
plt.annotate("offset text", xy=(2, 4),
xytext=(15, 15), textcoords="offset points",
arrowprops=dict(arrowstyle="->"))
# xytext in axes fraction
plt.annotate("axes corner", xy=(2, 4),
xytext=(0.8, 0.8), textcoords="axes fraction",
arrowprops=dict(arrowstyle="-|>"))
plt.show()그림 저장
savefig 기본
plt.savefig(path)는 현재 figure를 파일로 저장합니다. 중요한 것은 plt.show() '이전에' 호출하는 것입니다. show()가 끝나면서 그림을 닫거나 비울 수 있어 그 후 저장하면 빈 파일이 됩니다. 확장자가 형식을 자동으로 결정합니다(.png, .pdf, .svg, .jpg).
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 2])
# save BEFORE plt.show() -- show() clears the figure
plt.savefig("plot.png")
plt.savefig("plot.pdf")
plt.show()형식
용도별로 형식을 고르세요. 화면/웹은 PNG, 인쇄와 편집은 PDF 또는 SVG(벡터)로, 픽셀화 없이 확대됩니다. JPG는 사진 같은 이미지에만 쓰세요(선과 텍스트에서 선명도가 손실됨). 요소가 적은 플롯은 벡터 형식이 파일도 훨씬 작습니다. 확장자를 무시하려면 format=을 전달하세요.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
# raster formats (pixels)
plt.savefig("plot.png") # lossless, default
plt.savefig("plot.jpg", quality=95)
plt.savefig("plot.tiff", dpi=200)
# vector formats (scale without pixelation)
plt.savefig("plot.pdf") # best for publications
plt.savefig("plot.svg") # editable in Inkscape/Illustrator
# explicit format override
plt.savefig("plot.dat", format="png")DPI와 해상도
DPI(인치당 도트 수)는 래스터 출력의 해상도를 정합니다. 픽셀 크기 = figsize * dpi. 화면은 72~100 DPI로 충분하고 인쇄에는 300+ DPI가 필요합니다. 해상도 문제 자체를 피하려면 벡터 형식(PDF/SVG)으로 저장하세요. 스크립트 전반에서 고해상도를 유지하려면 rcParams에 savefig.dpi를 설정하세요.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3], [1, 4, 9])
# dpi controls pixel density: width_px = figsize[0] * dpi
plt.savefig("low.png", dpi=72) # 432 x 288 px
plt.savefig("high.png", dpi=300) # 1800 x 1200 px
# set a global default DPI
plt.rcParams["savefig.dpi"] = 300
plt.savefig("global.png")bbox_inches와 pad
기본적으로 savefig는 figure 사각형에 맞춰 잘라 내기 때문에 가장자리 근처의 레이블과 제목이 잘릴 수 있습니다. bbox_inches='tight'는 저장 영역을 모든 아티스트를 포함하도록 넓히고, pad_inches가 주변에 작은 여백을 더합니다. 거의 항상 원하는 동작이므로 rcParams['savefig.bbox']='tight'로 기본값으로 두세요.
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("With Long Title That Might Be Cut Off")
# tight bbox trims whitespace and keeps labels inside
plt.savefig("tight.png", bbox_inches="tight", pad_inches=0.1)
# trim even more aggressively
plt.savefig("tighter.png", bbox_inches="tight", pad_inches=0)
# preview the tight bounding box
# bbox = plt.savefig("x.png", bbox_inches="tight") # returns a Bbox투명 배경과 Facecolor
transparent=True는 그림 배경을 투명하게 합니다(PNG 알파 채널). 슬라이드나 웹 페이지 위에 플롯을 겹칠 때 이상적입니다. facecolor는 저장되는 배경색을 정합니다(화면 색을 덮어씀). 축 배경은 ax.set_facecolor()로 별도 제어합니다. 레이어드 디자인에 둘을 조합하세요.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_facecolor("#f0f0f0")
# transparent background (alpha channel)
plt.savefig("transparent.png", transparent=True)
# explicit figure face color
plt.savefig("colored.png", facecolor="lightblue", edgecolor="none")
# control which elements are saved
plt.savefig("full.png", facecolor=fig.get_facecolor())3D 플로팅 (mplot3d)
3D 축 설정
projection='3d'로 3D 축을 만듭니다(add_subplot 또는 subplots의 subplot_kw 사용). 모든 2D 메서드가 동작하며 z 관련 메서드(set_zlabel, plot_surface, scatter 등)가 추가됩니다. 3D 지원은 Matplotlib에 번들된 mplot3d 툴킷으로 추가 설치가 필요 없습니다.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
# add a 3D axes via projection
ax = fig.add_subplot(projection="3d")
# or from subplots
# fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("3D Axes")
plt.show()3D 산점도
3D 축에서 ax.scatter(x, y, z)는 공간에 점을 찍으며 s와 c 인자는 2D scatter와 동일하게 동작합니다. 색 매핑을 표시하려면 fig.colorbar(sc)를 추가하세요. 3D 산점도는 클러스터 탐색에 좋지만 정적 3D 플롯은 깊이가 숨겨질 수 있습니다. 인터랙티브하게 회전하거나 한 차원을 색으로 인코딩하세요.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
n = 200
x = rng.normal(0, 1, n)
y = rng.normal(0, 1, n)
z = rng.normal(0, 1, n)
c = np.sqrt(x**2 + y**2 + z**2)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
sc = ax.scatter(x, y, z, c=c, cmap="viridis")
fig.colorbar(sc, label="distance from origin")
ax.set_title("3D Scatter")
plt.show()3D 표면
plot_surface(X, Y, Z)는 색칠된 표면을 그립니다. X, Y, Z는 np.meshgrid로 만든 형상이 일치하는 2차원 배열이어야 합니다. rstride/cstride는 건너뛰는 격자점 수를 제어합니다(작을수록 부드럽지만 느림). cmap은 Z 기준으로 색을 입히고 컬러바를 추가하세요(3D figure에 맞게 shrink 사용).
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 80)
y = np.linspace(-5, 5, 80)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
surf = ax.plot_surface(X, Y, Z, cmap="coolwarm",
rstride=1, cstride=1,
linewidth=0, antialiased=True)
fig.colorbar(surf, shrink=0.5, aspect=10)
ax.set_title("3D Surface")
plt.show()3D 와이어프레임과 컨투어
plot_wireframe은 격자선만 그립니다(전체 표면보다 가볍고 구조 표시에 좋음). ax.contourf를 zdir='z'와 offset과 함께 쓰면 채워진 컨투어를 표면 아래 평면에 투영합니다. 흔한 '3D 아래 2D' 시각화입니다. 표면 + 투영 컨투어를 조합하면 풍부한 지형 플롯이 됩니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 30)
y = np.linspace(-3, 3, 30)
X, Y = np.meshgrid(x, y)
Z = X * np.exp(-X**2 - Y**2)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.plot_wireframe(X, Y, Z, color="black", rstride=1, cstride=1)
ax.set_title("Wireframe")
# 3D contour (filled) projected at the bottom
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.contourf(X, Y, Z, zdir="z", offset=-0.5, cmap="viridis")
ax.set_title("3D Contour")
plt.show()3D 막대
ax.bar3d(x, y, z, dx, dy, dz)는 (x, y) 위치에 밑면 z에서 시작해 너비 dx, dy, 높이 dz인 사각 막대를 그립니다. shade=True가 3D 느낌의 조명을 더합니다. meshgrid에서 시작할 때는 .ravel()로 좌표 배열을 평탄화하세요. 3D 막대는 읽기 어려울 수 있으니 가능하면 그룹 2D 막대를 권장합니다.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
x = np.arange(3)
y = np.arange(3)
X, Y = np.meshgrid(x, y)
X, Y = X.ravel(), Y.ravel()
Z = np.zeros_like(X)
dz = np.array([1, 2, 3, 2, 3, 1, 3, 1, 2])
ax.bar3d(X, Y, Z, dx=0.6, dy=0.6, dz=dz,
shade=True, color="tab:orange")
ax.set_title("3D Bar Chart")
plt.show()컨투어 플롯
컨투어 선
plt.contour(X, Y, Z)는 Z가 일정한 등고선을 그립니다. X, Y는 meshgrid에서 옵니다. levels는 컨투어 개수(또는 정확한 값)를 정합니다. plt.clabel(cs)은 각 선에 값을 레이블합니다. 선 컨투어는 정밀하지만 성깁니다. 채워진 영역은 contourf와 조합하세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
# line contours
cs = plt.contour(X, Y, Z, levels=15, colors="black", linewidths=0.8)
plt.clabel(cs, inline=True, fontsize=8)
plt.title("Contour Lines")
plt.colorbar(cs)
plt.show()채워진 컨투어
plt.contourf(끝의 'f'에 주의)는 컨투어 레벨 사이 영역을 색으로 채워 부드러운 히트맵 모양을 만듭니다. contour와 마찬가지로 격자화된 X, Y, Z가 필요합니다. levels가 해상도를 제어합니다. contourf는 온도, 고도, 확률 밀도 같은 2차원 스칼라 장을 표준적으로 시각화하는 방법입니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
cf = plt.contourf(X, Y, Z, levels=20, cmap="viridis")
plt.colorbar(cf, label="Z")
plt.title("Filled Contour")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()컨투어 레이블 (clabel)
plt.clabel(cs)은 컨투어 선에 Z 값 주석을 붙이며, inline=True는 레이블이 들어가도록 선을 끊습니다. fmt가 숫자 형식을 정합니다('%.2f' 또는 함수). levels=[...]로 특정 등고선만 레이블할 수 있습니다. 레이블된 컨투어는 컬러바 없이 정확한 값을 전달합니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = X * np.exp(-X**2 - Y**2)
cs = plt.contour(X, Y, Z, 10, colors="black")
plt.clabel(cs, inline=True, fontsize=9, fmt="%.2f")
# label only specific levels
# plt.clabel(cs, levels=[-0.1, 0, 0.1])
plt.title("Labeled Contours")
plt.show()컬러바
plt.colorbar(mappable)는 색 키를 추가합니다. 매핑을 알 수 있도록 contour/imshow/scatter의 반환값을 항상 전달하세요. set_label/set_ticks로 커스터마이징합니다. 서브플롯에서 컬러바는 축의 공간을 가져올 수 있으므로, ax= 인자 또는 fig.colorbar(mappable, ax=axes)로 여러 축에서의 배치를 제어하세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
y = np.linspace(0, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)
cf = plt.contourf(X, Y, Z, cmap="RdBu")
# basic colorbar
cb = plt.colorbar(cf)
cb.set_label("Z value")
cb.set_ticks([-2, -1, 0, 1, 2])
# place colorbar with specific size and padding
# cb = plt.colorbar(cf, fraction=0.046, pad=0.04)
plt.title("Colorbar Example")
plt.show()meshgrid와 griddata
contour/contourf는 규칙적 격자의 데이터가 필요합니다. 흩어진 샘플은 scipy.interpolate.griddata로 meshgrid에 보간하세요(방법: 'linear', 'nearest', 'cubic'). np.mgrid[...]는 범위에 대한 meshgrid의 편리한 축약입니다. 원래 점을 위에 그리면 데이터가 성긴 곳을 알 수 있습니다.
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
# scattered (x, y, z) samples
rng = np.random.default_rng(0)
pts = rng.uniform(-2, 2, (200, 2))
z = np.sin(pts[:,0]) * np.cos(pts[:,1])
# build a regular grid
grid_x, grid_y = np.mgrid[-2:2:100j, -2:2:100j]
# interpolate scattered data onto the grid
grid_z = griddata(pts, z, (grid_x, grid_y), method="cubic")
plt.contourf(grid_x, grid_y, grid_z, levels=20, cmap="plasma")
plt.scatter(pts[:,0], pts[:,1], c="white", s=5, alpha=0.5)
plt.colorbar(label="z")
plt.title("Scattered -> Grid -> Contour")
plt.show()이미지 표시 (imshow)
imshow 기본
plt.imshow(arr)는 2차원 배열을 히트맵으로, (H, W, 3) 3차원 배열을 RGB 이미지로 표시합니다. 기본 원점은 왼쪽 위(origin='upper')로 이미지 관례에 맞습니다. 수학 스타일 축에는 origin='lower'를 쓰세요. 깔끔한 이미지 표시를 위해 plt.axis('off')로 눈금을 숨깁니다.
import matplotlib.pyplot as plt
import numpy as np
# a 2D array is shown as a heatmap (color = value)
rng = np.random.default_rng(0)
img = rng.random((10, 10))
plt.imshow(img, cmap="viridis")
plt.colorbar(label="value")
plt.title("imshow of a 2D array")
plt.show()
# a 3D array (H, W, 3 or 4) is shown as an RGB(A) image
rgb = rng.integers(0, 256, (50, 50, 3), dtype=np.uint8)
plt.imshow(rgb)
plt.axis("off")
plt.title("RGB image")
plt.show()컬러맵과 컬러바
extent=[xmin, xmax, ymin, max]는 배열 픽셀을 데이터 좌표로 매핑합니다. 없으면 imshow는 픽셀 인덱스를 씁니다. origin='lower'는 0행을 아래에 둡니다(수학 관례). aspect='auto'는 이미지를 축에 맞게 늘리고, 기본 'equal'은 정사각 픽셀을 유지합 니다. colorbar에는 이미지 객체를 전달하세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2) / (X**2 + Y**2 + 1)
im = plt.imshow(Z, extent=[-3, 3, -3, 3], origin="lower",
cmap="RdBu", aspect="auto")
cb = plt.colorbar(im)
cb.set_label("intensity")
plt.title("imshow with extent")
plt.show()보간
interpolation은 확대 시 픽셀을 섞는 방식을 제어합니다. 'none'/'nearest'는 또렷한 블록(원시 픽셀 데이터 표시에 적합), 'bilinear'/'bicubic'은 픽셀 사이를 부드럽게 합니다(히트맵에 적합). 보간은 표시만 바꾸며 데이터 자체는 바뀌지 않습니다. 작은 배열에서는 셀 하나하나가 보여야 하므로 'nearest'가 오히려 원하는 경우가 많습니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(1)
small = rng.random((5, 5))
methods = ["none", "bilinear", "bicubic", "nearest"]
fig, axes = plt.subplots(1, 4, figsize=(12, 3))
for ax, m in zip(axes, methods):
ax.imshow(small, interpolation=m, cmap="magma")
ax.set_title(m)
ax.axis("off")
plt.tight_layout()
plt.show()vmin / vmax와 norm
vmin/vmax는 컬러맵에 매핑되는 데이터 범위를 고정합니다(이상치 클리핑). 비선형 매핑은 norm=을 사용하세요. 자릿수가 크게 다른 데이터에는 LogNorm, 의미 있는 중간점(예: 이상치 기준 0)에 발산 맵을 맞추려면 TwoSlopeNorm. norm과 vmin/vmax는 동시에 쓸 수 없으니 하나만 전달하세요.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm, TwoSlopeNorm
rng = np.random.default_rng(2)
Z = rng.random((50, 50)) * 1000 + 1
# clamp the colormap range
plt.imshow(Z, vmin=100, vmax=500, cmap="viridis")
plt.colorbar()
plt.title("clipped range")
plt.show()
# log-scaled colors
plt.imshow(Z, norm=LogNorm(vmin=1, vmax=1001), cmap="plasma")
plt.colorbar()
plt.title("log scale")
plt.show()
# diverging norm centered on a midpoint
# norm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=1)파일에서 이미지 표시
mpimg.imread는 이미지를 NumPy 배열로 읽습니다(PNG는 float 0-1, JPEG는 0-255 uint8). plt.imshow로 표시하고, plt.imsave는 배열을 다시 파일로 씁니다. RGB 이미지는 색이 유지되고, 단일 채널 이미지에는 cmap='gray'를 전달하세요. 본격적인 이미지 처 리에는 PIL/pillow가 더 강력합니다.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# read an image file into a numpy array
img = mpimg.imread("photo.png") # shape (H, W, 3) or (H, W, 4)
print(img.shape, img.dtype)
plt.imshow(img)
plt.axis("off")
plt.show()
# save the (possibly modified) array back to a file
# plt.imsave("out.png", img)
# drop the alpha channel if present
if img.shape[-1] == 4:
img = img[..., :3]극좌표 플롯
극좌표 축
projection='polar'는 축을 극좌표로 바꿉니다. x는 각도(theta, 라디안), y는 반지름(r)입니다. 모든 표준 메서드가 (theta, r)로 동작합니다. 극좌표 플롯은 방향성 데이터, 주기 함수, 원형 대칭에 이상적입니다. 눈금은 ax.set_thetagrids와 ax.set_rgrids로 설정합니다.
import matplotlib.pyplot as plt
import numpy as np
# create a polar axes via projection
fig = plt.figure()
ax = fig.add_subplot(projection="polar")
# or from subplots
# fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
theta = np.linspace(0, 2*np.pi, 100)
ax.plot(theta, np.sin(2*theta))
plt.show()극좌표 선 그래프
극좌표 축에서 plot(theta, r)은 theta가 각도, r이 반지름인 곡선을 그립니다. set_rmax는 반지름 범위를 잘라내고, set_rticks와 set_thetagrids가 반지름/각도 눈금 위치를 커스터마이징합니다. 극좌표 선 그래프는 주기 함수를 깔끔히 보여 줍니다. 사인파는 닫힌 고리로 감깁니다.
import matplotlib.pyplot as plt
import numpy as np
theta = np.linspace(0, 2*np.pi, 200)
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(theta, 1 + np.cos(theta), label="cardioid")
ax.plot(theta, np.abs(np.sin(2*theta)), label="rose")
ax.set_rmax(2.0)
ax.set_rticks([0.5, 1.0, 1.5])
ax.set_thetagrids([0, 90, 180, 270])
ax.legend(loc="upper right")
plt.show()레이더 / 스파이더 차트
레이더 차트는 범주마다 하나의 축을 갖는 극좌표 선 그래프입니다. 트릭은 첫 값을/각도를 끝에 덧붙여 곡선이 고리로 닫히게 하고, 내부를 alpha로 채우는 것입니다. xticks를 범주 각도로 설정하고 레이블하세요. 레이더는 다변량 프로필을 비교하지만 오도할 수 있으니 아껴 쓰세요.
import matplotlib.pyplot as plt
import numpy as np
labels = ["Speed", "Power", "Range", "Comfort", "Price"]
values = [8, 7, 6, 5, 9]
N = len(labels)
# close the loop
angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist()
values += values[:1]
angles += angles[:1]
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(angles, values, "o-")
ax.fill(angles, values, alpha=0.25)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
ax.set_title("Radar Chart")
plt.show()극좌표 막대 (로즈)
로즈(또는 극좌표 막대) 차트는 극좌표 축에서 ax.bar를 사용합니다. 각 막대는 각도 섹터를 차지합니다. 풍향이나 파도 주기 분포 같은 방향성 히스토그램에 유용합니다. (예시처럼) 반지름으로 막대 색을 입히면 추가 차원이 됩니다. bottom=으로 막대를 쌓거나 중심에서 오프셋할 수 있습니다.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
N = 12
theta = np.linspace(0, 2*np.pi, N, endpoint=False)
widths = 2*np.pi / N
radii = rng.uniform(1, 5, N)
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
bars = ax.bar(theta, radii, width=widths, bottom=0,
edgecolor="black")
# color bars by radius
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r / radii.max()))
ax.set_title("Rose Diagram")
plt.show()극좌표 설정
set_theta_zero_location('N')은 0 라디안을 위로 옮기고, set_theta_direction(-1)은 각도가 시계 방향으로 증가하게 합니다. 나침반 관례입니다. set_rlabel_position(angle)은 방사형 눈금 레이블을 원하는 각도로 옮겨 데이터와의 겹침을 피합니다. 이 조정으로 수학적 극좌표 플롯이 나침반 플롯이 됩니다.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(np.linspace(0, 2*np.pi, 100), np.linspace(0, 1, 100))
# rotate 0 degrees to the top, go clockwise
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
# radial limits and ticks
ax.set_rlim(0, 1.2)
ax.set_rticks([0.25, 0.5, 0.75, 1.0])
ax.set_rlabel_position(135) # move radial labels out of the way
# label directions in degrees
ax.set_thetagrids([0, 90, 180, 270], labels=["E","N","W","S"])
plt.show()트윈 축
twinx (보조 Y축)
ax.twinx()는 x축을 공유하고 오른쪽에 자체 y축을 갖는 새 axes를 만듭니다. 온도와 습도처럼 단위가 다른 두 수량을 함께 그리는 표준 방법입니다. 독자가 어느 눈금이 어느 시리즈인지 알도록 각 축과 눈금을 곡선 색에 맞춰 입히세요.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots()
ax1.plot(x, np.sin(x), "b-")
ax1.set_xlabel("x")
ax1.set_ylabel("sin(x)", color="b")
ax1.tick_params(axis="y", labelcolor="b")
# a second axes sharing the same x, with an independent y
ax2 = ax1.twinx()
ax2.plot(x, x*10, "r-")
ax2.set_ylabel("10*x", color="r")
ax2.tick_params(axis="y", labelcolor="r")
plt.title("twinx: two y-scales")
plt.show()twiny (보조 X축)
ax.twiny()는 수평 버전입니다. y축을 공유하지만 위에 자체 x축을 갖는 새 axes입니다. 같은 데이터를 두 x 스케일(미터와 피트, 초와 분)로 보여 줄 때 사용합니다. 같은 색 코딩 팁이 적용됩니다. 축 색을 해당 곡선과 맞추세요.
import matplotlib.pyplot as plt
import numpy as np
y = np.linspace(0, 10, 50)
fig, ax1 = plt.subplots()
ax1.plot(np.exp(y), y, "g-")
ax1.set_ylabel("y")
ax1.set_xlabel("exp(y)", color="g")
# second axes sharing y, independent x on top
ax2 = ax1.twiny()
ax2.plot(y**2, y, "m-")
ax2.set_xlabel("y^2", color="m")
plt.title("twiny: two x-scales")
plt.show()결합 트윈 차트
축을 트윈하면 각 axes에 자체 범례가 생깁니다. 하나의 결합 범례를 표시하려면 양쪽 축의 선 핸들을 리스트로 모아 ax1.legend(lines, labels)를 호출하세요. 이중 축 차트에서 단일 범례를 유지하는 관용적 방법으로, 독자가 두 시리즈를 한 번에 식별할 수 있습니다.
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 5, 100)
temp_c = 20 + 5*np.sin(t) # Celsius
humidity = 60 - 5*t # percent
fig, ax1 = plt.subplots(figsize=(8, 4))
l1, = ax1.plot(t, temp_c, "r-o", label="Temperature (C)")
ax1.set_xlabel("time (s)")
ax1.set_ylabel("Temperature (C)", color="r")
ax1.tick_params(axis="y", labelcolor="r")
ax2 = ax1.twinx()
l2, = ax2.plot(t, humidity, "b-s", label="Humidity (%)")
ax2.set_ylabel("Humidity (%)", color="b")
ax2.tick_params(axis="y", labelcolor="b")
# combine legends from both axes
lines = [l1, l2]
ax1.legend(lines, [l.get_label() for l in lines], loc="upper right")
plt.title("Temperature & Humidity")
plt.show()트윈 축 Despine
트윈 축은 위쪽 테두리가 자연히 이중으로 생깁니다. 더 깔끔하게 보이려면 양쪽 축의 위쪽 spines를 숨기고, 왼쪽/오른쪽 spines를 각각의 y축 색에 맞춰 입히세요. 색칠된 눈금 레이블과 결합하면 차트를 어지럽히지 않고 어느 눈금이 어느 곡선인지 명확히 알려 줍니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, np.sin(x), color="tab:blue")
ax2.plot(x, np.cos(x), color="tab:orange")
# remove the top spine so the two axes don't double-border
ax1.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)
# color the spines to match their axes
ax1.spines["left"].set_color("tab:blue")
ax2.spines["right"].set_color("tab:orange")
plt.title("Clean Twin Axes")
plt.show()단위가 다른 트윈 축
때로는 두 번째 시리즈가 아니라 단위를 변환한 보조 축(km/마일, C/F)만 필요합니다. twiny()를 만들고 set_xlim으로 범위를 맞춘 뒤, 변환된 값으로 xticks/xticklabels를 직접 설정하세요. 하나의 데이터 시리즈에 두 단위 체계를 주석으로 붙이는 것입니다.
import matplotlib.pyplot as plt
import numpy as np
km = np.linspace(0, 100, 50)
mile = km * 0.621371
fig, ax1 = plt.subplots()
ax1.plot(km, np.sin(km/10), "tab:purple")
ax1.set_xlabel("distance")
ax1.set_ylabel("signal", color="tab:purple")
ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim()) # align x limits
# relabel the top ticks in miles
new_ticks = np.array([0, 25, 50, 75, 100])
ax2.set_xticks(new_ticks)
ax2.set_xticklabels([f"{m:.0f}" for m in new_ticks*0.621371])
ax2.set_xlabel("miles")
plt.show()오차 막대와 채워진 영역
errorbar
plt.errorbar(x, y, yerr)는 수직 오차 막대가 있는 점을 그립니다. 불확실성이 있는 실험 데이터의 표준입니다. fmt는 플롯 형식 문자열입니다('o-' = 마커 + 선). ecolor, elinewidth, capsize가 오차 막대를 스타일링합니다. 수평 오차는 xerr=, 둘 다는 2차원 불확실성입니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
y = np.exp(-x)
yerr = 0.1 + 0.1*x # error grows with x
plt.errorbar(x, y, yerr=yerr, fmt="o-", color="tab:blue",
ecolor="gray", elinewidth=1.5, capsize=4,
markersize=6, label="exp(-x) +/- err")
plt.legend()
plt.title("Error Bar Plot")
plt.show()비대칭 오차
비대칭 불확실성은 yerr을 2 x N 배열로 전달합니다. 0행은 아래쪽(하향) 오차, 1행은 위쪽(상향) 오차입니다. 오차가 치우친 경우(예: 포아송 계수)에 흔합니다. 수평 비대칭 불확실성인 xerr에도 같은 패턴이 적용됩니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.array([2, 3, 5, 4, 6])
# separate lower and upper errors (each a 1-D array)
yerr = [[0.5, 1, 0.8, 0.6, 1.2], # lower
[1.0, 0.8, 1.5, 1.0, 0.7]] # upper
plt.errorbar(x, y, yerr=yerr, fmt="s", color="tab:green",
capsize=5)
plt.title("Asymmetric Error Bars")
plt.show()
# horizontal asymmetric errors work the same way
# xerr = [[...lower...], [...upper...]]fill_between
fill_between(x, y1, y2)는 두 y 곡선 사이 영역을 채웁니다. 신뢰 구간, 오차 밴드, 범위에 완벽합니다. where=은 부울 배열이 True인 곳만 채웁니다(곡선이 교차하면 interpolate=True). alpha < 1이면 밴드 아래 곡선이 계속 보입니다.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
std = 0.2
plt.plot(x, y, "b-", label="mean")
# shade +/- one standard deviation
plt.fill_between(x, y - std, y + std, color="blue", alpha=0.2,
label="+/- 1 std")
# shade only where a condition holds
plt.fill_between(x, y, 0, where=(y > 0), color="green", alpha=0.2,
label="y > 0")
plt.legend()
plt.show()stackplot
plt.stackplot(x, y1, y2, ...)는 여러 시리즈를 위로 쌓아 연속 x(주로 시간)에 걸친 총합과 구성을 보여 줍니다. 누적 막대와 달리 연속 데이터용입니다. 전체 높이는 모든 시리즈의 합입니다. 층 사 이 경계가 보이도록 alpha와 함께 서로 다른 색을 쓰세요.
import matplotlib.pyplot as plt
import numpy as np
years = np.arange(2010, 2021)
a = np.array([10, 12, 14, 15, 17, 18, 20, 22, 23, 25, 27])
b = np.array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
c = np.array([ 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10])
plt.stackplot(years, a, b, c, labels=["A", "B", "C"],
colors=["#4C72B0", "#55A868", "#C44E52"], alpha=0.8)
plt.legend(loc="upper left")
plt.title("Stacked Area Chart")
plt.xlabel("year")
plt.ylabel("value")
plt.show()fill (다각형)
plt.fill(x, y)는 임의 다각형을 닫아 채웁니다. 영역 강조나 곡선 아래 음영에 유용합니다. 곡선 아래를 채우려면 x 값에 역순을 이어 붙이고 y 값에 0을 이어 붙입니다. 서로 분리된 여러 영역은 2차원 배열을 전달하거나 fill을 반복 호출하세요.
import matplotlib.pyplot as plt
import numpy as np
# fill a closed polygon defined by its vertices
x = [0, 1, 1, 0, 0]
y = [0, 0, 1, 1, 0]
plt.fill(x, y, color="tab:cyan", alpha=0.5)
# shade under a curve
xs = np.linspace(0, 2*np.pi, 100)
ys = np.sin(xs)
plt.fill(np.r_[xs, xs[::-1]],
np.r_[ys, np.zeros_like(ys)],
color="tab:orange", alpha=0.3)
plt.title("Filled Polygons")
plt.show()Seaborn 통합
Seaborn 소개
Seaborn은 Matplotlib 위에 만들어진 고수준 통계 플로팅 라이브러리입니다. pandas DataFrame을 받고, 그룹핑/집계를 처리하며, 더 예쁜 기본값을 씁니다. 모든 Seaborn 함수는 Matplotlib Axes(또는 Figure)를 반환하므로 plt/ax 호출로 계속 커스터마이징할 수 있습니다. Seaborn 스타일로 전환하려면 sns.set_theme()를 한 번 호출하세요.
# install seaborn
pip install seaborn
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Seaborn is built ON matplotlib: any sns plot returns an Axes
# and accepts an ax= argument, so you can mix freely.
sns.set_theme() # apply seaborn's default style
tips = sns.load_dataset("tips")
ax = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
ax.set_title("Tips dataset")
plt.show()Seaborn 스타일
sns.set_style은 축 모양(격자, 배경)을 정하고, set_context는 출력 매체에 맞춰 폰트/선을 스케일합니다('paper', 'talk', 'poster'), set_palette는 색상 사이클을 정합니다. sns.despine()은 위/오른쪽 spines를 제거합니다. 한두 줄로 세련된 기본 모양이 완성됩니다.
import seaborn as sns
import matplotlib.pyplot as plt
# five built-in themes: darkgrid, whitegrid, dark, white, ticks
sns.set_style("whitegrid")
sns.set_context("notebook") # paper, notebook, talk, poster
# set the color palette
sns.set_palette("Set2")
import numpy as np
for i in range(4):
plt.plot(np.arange(10), np.arange(10)+i)
plt.title("Seaborn-styled")
plt.show()
# remove the top/right spines (despine) for a clean look
# sns.despine()relplot (관계형)
sns.relplot은 관계형 플롯의 figure 수준 인터페이스입니다. kind='scatter'(기본) 또는 'line'. col/row가 데이터를 자동으로 서브플롯(faceting)으로 분할합니다. 수동 서브플롯보다 훨씬 쉽습니다. FacetGrid를 반환하며 .fig와 .axes로 Matplotlib 수준에서 제목과 레이아웃을 다듬을 수 있습니다.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# scatter or line, faceted by a categorical variable
g = sns.relplot(data=tips, x="total_bill", y="tip",
hue="smoker", style="time", col="day",
kind="scatter", height=3, aspect=1.2)
g.fig.suptitle("Tips by day", y=1.03)
plt.show()histplot과 kdeplot
sns.histplot은 폐기된 distplot의 현대적 대체물입니다. 히스토그램을 그리고 커널 밀도 추정을 겹칠 수 있습니다(kde=True). stat='density'로 정규화하고, common_norm=False는 그룹을 독립적으로 정규화합니다. sns.kdeplot은 매끄러운 밀도 곡선만 그려 분포 비교에 유용합니다.
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# histogram with an overlaid KDE (density curve)
sns.histplot(data=tips, x="total_bill", bins=20, kde=True,
hue="time", stat="density", common_norm=False)
plt.title("Histogram + KDE")
plt.show()
# standalone KDE
plt.figure()
sns.kdeplot(data=tips, x="total_bill", hue="time", fill=True)
plt.show()heatmap
sns.heatmap은 색으로 코딩된 행렬을 그리며 셀 주석을 넣을 수 있습니다(annot=True). center=0과 발산 컬러맵(coolwarm)을 쓰면 양수/음수 상관 이 시각적으로 구분됩니다. plt.imshow + plt.text + colorbar를 감싸 상관 행렬과 혼동 행렬에 필요한 보일러플레이트를 크게 줄여 줍니다.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# correlation matrix
tips = sns.load_dataset("tips")
num = tips.select_dtypes("number").drop(columns=["size"])
corr = num.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", center=0,
vmin=-1, vmax=1, square=True,
linewidths=0.5, fmt=".2f")
plt.title("Correlation Heatmap")
plt.show()pairplot과 violinplot
sns.pairplot은 모든 숫자 열 쌍의 산점도 격자를 만들고 범주형 hue로 색을 입힙니다. 새 데이터셋의 관계를 탐색하는 가장 빠른 방법입니다. sns.violinplot은 박스 플롯과 밀도 추정을 결합해 그룹별 분포 모양을 보여 줍니다. 둘 다 내부는 순수 Matplotlib이므로 추가 커스터마이징이 가능합니다.
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
# scatter matrix: every numeric column vs every other
g = sns.pairplot(iris, hue="species", height=2.5)
g.fig.suptitle("Iris pairplot", y=1.01)
plt.show()
# violin plot: box + kernel density on each side
plt.figure()
sns.violinplot(data=iris, x="species", y="sepal_length",
inner="quartile")
plt.show()인터랙티브와 애니메이션
슬라이더 위젯
matplotlib.widgets.Slider는 인터랙티브 슬라이더를 추가합니다. 전용 axes를 만들고(보통 plt.axes([left, bottom, width, height]를 figure 분수로 figure 하단에), on_changed에 콜백을 연결해 그 안에서 플롯 데이터를 갱신합니다. 갱신을 반영하려면 fig.canvas.draw_idle()을 호출하세요. 인터랙티브 백엔드(Agg는 불가)가 필요합니다.
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
x = np.linspace(0, 10, 500)
line, = ax.plot(x, np.sin(x))
# axes for the slider
ax_freq = plt.axes([0.2, 0.1, 0.6, 0.03])
slider = Slider(ax_freq, "freq", 0.1, 5.0, valinit=1.0)
def update(val):
line.set_ydata(np.sin(slider.val * x))
fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()버튼
matplotlib.widgets.Button은 클릭 가능한 버튼을 추가합니다. 슬라이더처럼 전용 axes가 필요합니다(figure 분수 좌표로 배치). 콜백은 보통 무시해도 되는 이벤트 객체를 받습니다. 여러 위젯(슬라이더, 버튼, 체크박스)을 조합하면 Matplotlib만으로 간단한 데이터 탐색 대시보드를 만들 수 있습니다.
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
(ln,) = ax.plot(np.random.rand(10))
ax_btn = plt.axes([0.7, 0.05, 0.2, 0.075])
btn = Button(ax_btn, "Resample")
def reshuffle(event):
ln.set_ydata(np.random.rand(10))
fig.canvas.draw_idle()
btn.on_clicked(reshuffle)
plt.show()CheckButtons
CheckButtons는 체크박스 목록을 렌더링합니다. 콜백은 토글된 레이블의 텍스트를 받으므로, 이를 비교해 각 아티스트의 표시 여부를 바꿉니다. 보는 사람이 시리즈를 켜고 끄게 할 때 사용합니다. 모든 위젯처럼 인터랙티브 백엔드가 필요하고 창이 열려 있어야 합니다.
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import numpy as np
x = np.linspace(0, 5, 200)
l1, = plt.plot(x, np.sin(x), label="sin")
l2, = plt.plot(x, np.cos(x), label="cos")
plt.subplots_adjust(right=0.8)
rax = plt.axes([0.82, 0.4, 0.15, 0.2])
check = CheckButtons(rax, ["sin", "cos"], [True, True])
def toggle(label):
if label == "sin": l1.set_visible(not l1.get_visible())
if label == "cos": l2.set_visible(not l2.get_visible())
plt.draw()
check.on_clicked(toggle)
plt.show()커서와 마우스 이벤트
mpl_connect는 이벤트(button_press_event, motion_notify_event, key_press_event, scroll_event)를 콜백에 연결합니다. 이벤트 객체는 event.xdata/event.ydata(데이터 좌표)와 event.inaxes(어느 축인지, 또는 None)를 담습니다. 십자선, 클릭 주석, 커스텀 줌 도구 같은 커스텀 인터랙션의 기반입니다.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
def on_click(event):
if event.inaxes != ax:
return
print(f"clicked at x={event.xdata:.2f} y={event.ydata:.2f}")
def on_move(event):
if event.inaxes == ax:
ax.set_title(f"x={event.xdata:.2f}, y={event.ydata:.2f}")
fig.canvas.draw_idle()
fig.canvas.mpl_connect("button_press_event", on_click)
fig.canvas.mpl_connect("motion_notify_event", on_move)
plt.show()애니메이션 (FuncAnimation)
FuncAnimation은 update(frame)를 반복 호출해 애니메이션을 구동합니다. blit=True로 속도를 내려면 update가 (튜플로) 바뀐 아티스트를 반환해야 합니다. interval은 프레임 사이 지연(ms)입니다. 저장에는 writer가 필요합니다('ffmpeg'는 mp4, 'pillow'는 gif). 애니메이션 객체(ani)를 참조로 유지하세요. 그렇지 않으면 가비지 컬렉션되어 멈춥니다.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
line, = ax.plot(x, np.sin(x))
def update(frame):
line.set_ydata(np.sin(x + frame / 10.0))
return line,
ani = animation.FuncAnimation(fig, update, frames=100,
interval=50, blit=True, repeat=True)
# save to a file (requires ffmpeg or pillow installed)
# ani.save("wave.mp4", writer="ffmpeg")
# ani.save("wave.gif", writer="pillow")
plt.show()관련 Matplotlib 스니펫
Copy-paste ready code for common tasks.
Line Plot
Plot lines with markers, colors, and styles.
Bar Chart
Draw vertical, horizontal, and grouped bars.
Scatter Plot
Visualize relationships with size and color encodings.
Subplots
Arrange multiple axes with subplots and GridSpec.
Labels and Legend
Annotate plots with text, arrows, and legend options.
Styles and Themes
Apply built-in styles and customize rcParams.
Save Figure
Export figures to PNG, PDF, and SVG with DPI control.
3D Plot
Render surfaces and scatter in 3D.
Was this helpful?