Matplotlib 기초 | Python 데이터 시각화 완벽 정리
이 글의 핵심
Matplotlib 기초에 대한 실전 가이드입니다. Python 데이터 시각화 완벽 정리 등을 예제와 함께 상세히 설명합니다.
들어가며
”데이터를 그림으로”
Matplotlib은 데이터 시각화를 위한 Python의 표준 라이브러리입니다.
1. Matplotlib 기본
설치
pip install matplotlib
첫 그래프
plt.plot(x, y)는 가로축·세로축 좌표 쌍을 이은 선을 그립니다. 보고서에 넣을 도표의 뼈대는 plot으로 잡고, xlabel·ylabel·title로 읽는 사람이 축 의미를 알 수 있게 적어 줍니다.
import matplotlib.pyplot as plt
# 데이터
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 그래프 그리기
plt.plot(x, y)
plt.xlabel('X축')
plt.ylabel('Y축')
plt.title('선 그래프')
plt.show()
2. 선 그래프
기본 선 그래프
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='sin(x)', color='blue', linestyle='-')
plt.plot(x, y2, label='cos(x)', color='red', linestyle='--')
plt.xlabel('x')
plt.ylabel('y')
plt.title('삼각함수')
plt.legend()
plt.grid(True)
plt.show()
3. 막대 그래프
기본 막대 그래프
categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 55]
plt.bar(categories, values, color='skyblue')
plt.xlabel('카테고리')
plt.ylabel('값')
plt.title('막대 그래프')
plt.show()
가로 막대 그래프
plt.barh(categories, values, color='lightgreen')
plt.xlabel('값')
plt.ylabel('카테고리')
plt.title('가로 막대 그래프')
plt.show()
4. 히스토그램
# 정규 분포 데이터
data = np.random.randn(1000)
plt.hist(data, bins=30, color='purple', alpha=0.7, edgecolor='black')
plt.xlabel('값')
plt.ylabel('빈도')
plt.title('히스토그램')
plt.show()
5. 산점도
x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('산점도')
plt.show()
6. 여러 서브플롯
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# 1번 그래프
axes[0, 0].plot([1, 2, 3], [1, 4, 9])
axes[0, 0].set_title('선 그래프')
# 2번 그래프
axes[0, 1].bar(['A', 'B', 'C'], [3, 7, 5])
axes[0, 1].set_title('막대 그래프')
# 3번 그래프
axes[1, 0].hist(np.random.randn(100), bins=20)
axes[1, 0].set_title('히스토그램')
# 4번 그래프
axes[1, 1].scatter(np.random.rand(50), np.random.rand(50))
axes[1, 1].set_title('산점도')
plt.tight_layout()
plt.show()
7. 실전 예제
판매 데이터 시각화
import matplotlib.pyplot as plt
import pandas as pd
# 데이터
sales_data = pd.DataFrame({
'month': ['1월', '2월', '3월', '4월', '5월', '6월'],
'sales': [150, 180, 165, 220, 250, 240],
'profit': [30, 45, 35, 60, 75, 70]
})
# 그래프
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 매출 추이
ax1.plot(sales_data['month'], sales_data['sales'],
marker='o', linewidth=2, markersize=8)
ax1.set_title('월별 매출 추이', fontsize=14, fontweight='bold')
ax1.set_xlabel('월')
ax1.set_ylabel('매출 (만원)')
ax1.grid(True, alpha=0.3)
# 수익 막대 그래프
ax2.bar(sales_data['month'], sales_data['profit'],
color='green', alpha=0.7)
ax2.set_title('월별 수익', fontsize=14, fontweight='bold')
ax2.set_xlabel('월')
ax2.set_ylabel('수익 (만원)')
plt.tight_layout()
plt.savefig('sales_report.png', dpi=300)
plt.show()
그래프 스타일·폰트·크기 한 번에 맞추기
Matplotlib은 보고서에 넣을 도표를 그리는 도구입니다. style로 전체 톤을 맞추고, 한글은 OS에 맞는 폰트 이름을 rcParams에 지정해야 깨지지 않습니다. figsize와 색 팔레트를 먼저 정해 두면 여러 축을 그릴 때도 일관된 느낌을 유지하기 쉽습니다.
# 스타일 적용
plt.style.use('seaborn-v0_8')
# 한글 폰트 설정
plt.rcParams['font.family'] = 'Malgun Gothic'
plt.rcParams['axes.unicode_minus'] = False
# 그래프 크기
plt.figure(figsize=(10, 6))
# 색상
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1']
실전 심화 보강
실전 예제: 회귀선이 있는 산점도 + 잔차 플롯 (완전 실행 예)
아래 스크립트는 numpy로 합성 데이터를 만들고, polyfit으로 1차 회귀선을 그린 뒤 잔차 분포를 함께 봅니다. 보고서용으로 savefig까지 포함했습니다.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
x = np.linspace(0, 10, 80)
y = 2.5 * x + 1.0 + rng.normal(0, 1.8, size=x.shape)
coef = np.polyfit(x, y, 1)
y_hat = np.poly1d(coef)(x)
residuals = y - y_hat
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4), constrained_layout=True)
ax1.scatter(x, y, alpha=0.7, label="관측")
ax1.plot(x, y_hat, color="crimson", linewidth=2, label="1차 회귀")
ax1.set_title("산점도와 회귀선")
ax1.legend()
ax1.grid(True, alpha=0.3)
ax2.hist(residuals, bins=18, color="steelblue", edgecolor="black", alpha=0.85)
ax2.set_title("잔차 분포")
ax2.grid(True, alpha=0.3)
fig.savefig("regression_residuals.png", dpi=200)
plt.show()
자주 하는 실수
- **
plt.show()후savefig**를 호출해 빈 파일이 저장되는 경우(순서를 바꿔야 함). - 한글 레이블이 깨져 보고서가 unusable이 되는 경우(운영체제별 폰트 설정 필요).
- 객체지향 API와
pyplot상태 머신을 섞어 축이 엉뚱한 서브플롯에 그려지는 경우.
주의사항
- 과학 출판물은 벡터 포맷(PDF/SVG)을 선호합니다. 비트맵은
dpi를 명시하세요. - 색맹 친화 팔레트(
colorblind스타일,tab10대신cividis등)를 검토하세요.
실무에서는 이렇게
- 반복되는 스타일은
matplotlibrc또는plt.style.context로 팀 공통화합니다. - 대시보드가 아니라 리포트 자동화라면
plt.close(fig)로 Figure를 닫아 메모리를 반환합니다.
비교 및 대안
| 도구 | 장면 |
|---|---|
| Matplotlib | 세밀한 제어, 논문·백엔드 렌더 |
| Seaborn | 통계 플롯 빠른 프로토타입 |
| Plotly | 인터랙티브 웹 |
추가 리소스
정리
핵심 요약
- Matplotlib: Python 시각화 라이브러리
- pyplot: 간단한 그래프 API
- 그래프 종류: 선, 막대, 히스토그램, 산점도
- 서브플롯: 여러 그래프 배치
- 스타일: 색상, 폰트, 레이아웃
다음 단계
- 데이터 전처리
- 실전 데이터 분석
관련 글
- Python 환경 설정 | Windows/Mac에서 Python 설치하고 시작하기