포스트

[Python 100일 챌린지] Day 67 - Matplotlib 기초

[Python 100일 챌린지] Day 67 - Matplotlib 기초

데이터를 그래프로 표현해봅시다! 📈

숫자만 보면 모르겠던 것들이 그래프로 보면 한눈에! Python으로 예쁜 차트 만들기, 생각보다 쉬워요! 🎨

(30분 완독 ⭐⭐)

🎯 오늘의 학습 목표

📚 사전 지식


🎯 학습 목표 1: Matplotlib 시작하기

1.1 설치 및 임포트

1
pip install matplotlib
1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt

# 한글 폰트 설정 (Mac)
plt.rcParams['font.family'] = 'AppleGothic'
# Windows의 경우
# plt.rcParams['font.family'] = 'Malgun Gothic'

# 마이너스 기호 깨짐 방지
plt.rcParams['axes.unicode_minus'] = False

1.2 첫 번째 그래프

1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt

# 데이터
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# 그래프 그리기
plt.plot(x, y)

# 화면에 표시
plt.show()

1.3 기본 구조

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt

# 1. Figure (도화지) 생성
fig, ax = plt.subplots()

# 2. 데이터 그리기
ax.plot([1, 2, 3], [1, 4, 9])

# 3. 꾸미기
ax.set_title('제곱 그래프')
ax.set_xlabel('X축')
ax.set_ylabel('Y축')

# 4. 표시
plt.show()

🎯 학습 목표 2: 선 그래프 그리기

2.1 기본 선 그래프

1
2
3
4
5
6
7
8
9
10
import matplotlib.pyplot as plt

months = ['1월', '2월', '3월', '4월', '5월']
sales = [100, 120, 115, 130, 145]

plt.plot(months, sales)
plt.title('월별 매출')
plt.xlabel('')
plt.ylabel('매출(만원)')
plt.show()

2.2 여러 선 그리기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt

months = ['1월', '2월', '3월', '4월', '5월']
product_a = [100, 120, 115, 130, 145]
product_b = [80, 95, 110, 105, 120]

plt.plot(months, product_a, label='제품A')
plt.plot(months, product_b, label='제품B')

plt.title('제품별 월 매출')
plt.xlabel('')
plt.ylabel('매출(만원)')
plt.legend()  # 범례 표시
plt.show()

2.3 선 스타일 변경

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [1, 4, 9, 16, 25]

# 다양한 스타일
plt.plot(x, y1, 'r-', label='선형')      # 빨간 실선
plt.plot(x, y2, 'b--', label='제곱')     # 파란 점선

# 마커 추가
# plt.plot(x, y1, 'ro-')   # 빨간 원형 마커 + 실선
# plt.plot(x, y2, 'bs--')  # 파란 사각 마커 + 점선

plt.legend()
plt.show()

스타일 옵션:

  • 색상: r(빨강), b(파랑), g(초록), k(검정)
  • 선: -(실선), --(점선), :(점), -.(점선혼합)
  • 마커: o(원), s(사각), ^(삼각), *(별)

🎯 학습 목표 3: 막대 그래프 그리기

3.1 기본 막대 그래프

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt

categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 35]

plt.bar(categories, values)
plt.title('카테고리별 값')
plt.show()

3.2 가로 막대 그래프

1
2
3
4
5
6
7
8
9
import matplotlib.pyplot as plt

categories = ['Python', 'Java', 'JavaScript', 'C++']
popularity = [30, 25, 20, 15]

plt.barh(categories, popularity)
plt.title('프로그래밍 언어 인기도')
plt.xlabel('인기도 (%)')
plt.show()

3.3 그룹 막대 그래프

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import matplotlib.pyplot as plt
import numpy as np

categories = ['1분기', '2분기', '3분기', '4분기']
product_a = [100, 120, 130, 150]
product_b = [80, 100, 110, 120]

x = np.arange(len(categories))
width = 0.35

fig, ax = plt.subplots()
ax.bar(x - width/2, product_a, width, label='제품A')
ax.bar(x + width/2, product_b, width, label='제품B')

ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.legend()
ax.set_title('분기별 제품 매출')
plt.show()

🎯 학습 목표 4: 그래프 꾸미기

4.1 제목과 레이블

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)

# 제목 (폰트 크기 지정)
plt.title('매출 추이', fontsize=16)

# 축 레이블
plt.xlabel('', fontsize=12)
plt.ylabel('매출(억)', fontsize=12)

plt.show()

4.2 그리드와 범례

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]

plt.plot(x, y1, label='A팀')
plt.plot(x, y2, label='B팀')

# 그리드 추가
plt.grid(True, linestyle='--', alpha=0.7)

# 범례 위치 지정
plt.legend(loc='upper left')  # 왼쪽 위

plt.title('팀별 성과')
plt.show()

4.3 색상과 스타일

1
2
3
4
5
6
7
8
9
10
11
import matplotlib.pyplot as plt

categories = ['A', 'B', 'C', 'D']
values = [25, 40, 30, 35]

# 색상 지정
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']

plt.bar(categories, values, color=colors)
plt.title('컬러풀한 차트')
plt.show()

4.4 그래프 저장

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

plt.plot(x, y)
plt.title('저장할 그래프')

# 파일로 저장
plt.savefig('my_chart.png', dpi=300, bbox_inches='tight')
# dpi: 해상도, bbox_inches='tight': 여백 최소화

plt.show()

💡 실전 팁

✅ 자주 쓰는 패턴

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

# 여러 그래프 한 번에 (subplot)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))

axes[0].plot([1,2,3], [1,2,3])
axes[0].set_title('그래프 1')

axes[1].bar(['A','B','C'], [10,20,15])
axes[1].set_title('그래프 2')

plt.tight_layout()  # 자동 간격 조정
plt.show()

✅ 한글 폰트 문제 해결

1
2
3
4
5
6
7
8
9
10
11
12
import matplotlib.pyplot as plt
import platform

# OS별 자동 설정
if platform.system() == 'Darwin':  # Mac
    plt.rcParams['font.family'] = 'AppleGothic'
elif platform.system() == 'Windows':
    plt.rcParams['font.family'] = 'Malgun Gothic'
else:  # Linux
    plt.rcParams['font.family'] = 'NanumGothic'

plt.rcParams['axes.unicode_minus'] = False

🧪 연습 문제

문제: 월별 매출 시각화

다음 데이터로 1) 선 그래프, 2) 막대 그래프를 각각 그리세요.

1
2
months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales = [120, 135, 128, 145, 160, 175]
정답 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import matplotlib.pyplot as plt

# 한글 폰트 설정
plt.rcParams['font.family'] = 'AppleGothic'
plt.rcParams['axes.unicode_minus'] = False

months = ['1월', '2월', '3월', '4월', '5월', '6월']
sales = [120, 135, 128, 145, 160, 175]

# 1. 선 그래프
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

axes[0].plot(months, sales, 'bo-', linewidth=2, markersize=8)
axes[0].set_title('월별 매출 추이 (선 그래프)', fontsize=14)
axes[0].set_xlabel('')
axes[0].set_ylabel('매출(만원)')
axes[0].grid(True, linestyle='--', alpha=0.7)

# 2. 막대 그래프
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
axes[1].bar(months, sales, color=colors)
axes[1].set_title('월별 매출 현황 (막대 그래프)', fontsize=14)
axes[1].set_xlabel('')
axes[1].set_ylabel('매출(만원)')

plt.tight_layout()
plt.show()

📝 오늘 배운 내용 정리

  1. 기본 구조: plt.plot(), plt.show()
  2. 선 그래프: plt.plot(x, y) - 추세 표현
  3. 막대 그래프: plt.bar(), plt.barh() - 비교 표현
  4. 꾸미기: title(), xlabel(), legend(), grid()
  5. 저장: plt.savefig('파일명.png')

📚 이전 학습

Day 66: Pandas 그룹화와 집계 ⭐⭐

📚 다음 학습

Day 68: 데이터 시각화 실전 ⭐⭐


“보이지 않던 인사이트가 그래프로 보여요!” 📈

Day 67/100 Phase 7: 데이터 분석 기초 #100DaysOfPython
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.