Matplotlib
Matplotlib이란?
파이썬에서 정적, 애니메이션, 대화형 데이터 시각화를 만들기 위해 가장 널리 사용되는 오픈소스 플로팅 라이브러리입니다. 2D 및 3D 그래픽을 모두 지원하며, 학술 논문용 고품질 그래프부터 간단한 데이터 탐색용 차트까지 다양한 시각화 결과물을 생성할 수 있습니다.
- 다양한 그래프 지원: 선 그래프, 산점도, 히스토그램, 막대 그래프, 파이 차트 등을 그릴 수 있습니다.
- 뛰어난 호환성: Numpy 배열이나 Pandas 데이터프레임과 완벽하게 연동됩니다.
- 세밀한 커스터마이징: 축, 라벨, 범례, 색상 등 그래프의 모든 시각적 요소를 직접 제어할 수 있습니다.
- 여러 포맷 저장: 완성된 그래프를 PNG, JPG, PDF, SVG 등의 파일로 내보낼 수 있습니다.
설치
pip install matplotlib
사용
import matplotlib.pyplot as plt
import numpy as np
1. 선 그래프 (Line Plot)
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,4,9,16]
plt.plot(x, y)
plt.show()
스타일 지정
plt.plot(x, y,
color='red',
linestyle='--',
marker='o')
plt.show()
옵션설명
| color | 선 색상 |
| linestyle | 선 스타일 |
| marker | 데이터 표시 모양 |
| linewidth | 선 두께 |
2. 제목과 축 라벨
plt.plot(x, y)
plt.title("성적 변화")
plt.xlabel("시험 횟수")
plt.ylabel("점수")
plt.show()
3. 범례(Legend)
그래프가 여러 개일 때 사용
plt.plot([1,2,3], [2,4,6], label="A반")
plt.plot([1,2,3], [1,3,5], label="B반")
plt.legend()
plt.show()
위치 지정
plt.legend(loc='upper left')
자주 사용하는 위치
- best
- upper right
- upper left
- lower right
- lower left
4. 축 범위 지정
그래프 표시 범위 설정
plt.plot(x, y)
plt.xlim(0, 5)
plt.ylim(0, 20)
plt.show()
또는
plt.axis([0,5,0,20])
# [xmin, xmax, ymin, ymax]
plt.axis([0,5,0,20])
5. 격자(Grid)
데이터 보기 쉽게 만들기
plt.plot(x, y)
plt.grid(True)
plt.show()
Y축만
plt.grid(True, axis='y')
투명도
plt.grid(True,
linestyle='--',
alpha=0.5)
6. 눈금(Ticks)
축 눈금 변경
plt.xticks([1,2,3],
['1월','2월','3월'])
plt.yticks([0,50,100])
결과
1월 2월 3월
7. Figure 크기 설정
그래프 전체 크기
plt.figure(figsize=(10,6))
plt.plot(x,y)
plt.show()
# 가로 10인치
# 세로 6인치
8. 막대 그래프 (Bar Chart)
카테고리 비교
years = ['2018','2019','2020']
values = [100,400,900]
plt.bar(years, values)
plt.show()
색상 지정
plt.bar(years,
values,
color=['red','green','blue'])
9. 가로 막대 그래프
plt.barh(years, values)
plt.show()
10. 산점도 (Scatter Plot)
데이터 분포 확인
import numpy as np
x = np.random.rand(50)
y = np.random.rand(50)
plt.scatter(x, y)
plt.show()
점 크기 지정
plt.scatter(x, y,
s=100)
옵션설명
| s | 점 크기 |
| c | 점 색상 |
11. 히스토그램 (Histogram)
데이터 빈도수 확인
scores = [60,70,80,90,80,75,65]
plt.hist(scores)
plt.show()
구간 개수 지정
plt.hist(scores,
bins=5)
12. 파이 차트 (Pie Chart)
비율 표현
ratio = [40,30,20,10]
labels = ['A','B','C','D']
plt.pie(ratio,
labels=labels)
plt.show()
퍼센트 표시
plt.pie(ratio,
labels=labels,
autopct='%.1f%%')
plt.show()
13. 여러 그래프 출력 (subplot)
한 화면에 여러 그래프
plt.subplot(1,2,1)
plt.plot([1,2,3],[1,4,9])
plt.subplot(1,2,2)
plt.plot([1,2,3],[9,4,1])
plt.show()
subplot(행, 열, 위치)
예시
plt.subplot(2,1,1)
plt.plot(...)
plt.subplot(2,1,2)
plt.plot(...)
위아래 배치
14. 그래프 저장
이미지 파일로 저장
plt.plot([1,2,3],[1,4,9])
plt.savefig("graph.png")
plt.show()
해상도 지정
plt.savefig("graph.png",
dpi=300)
자주 사용하는 마커
마커모양
| o | 원 |
| s | 사각형 |
| ^ | 삼각형 |
| x | 엑스 |
| * | 별 |
| d | 마름모 |
plt.plot(x, y, marker='o')
자주 사용하는 선 스타일
스타일설명
| - | 실선 |
| -- | 점선 |
| : | 도트선 |
| -. | 점-대시선 |
plt.plot(x, y, '--')
ex) 실무에서 가장 많이 쓰는 패턴
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1,6)
y = [10,20,15,30,25]
plt.figure(figsize=(8,5))
plt.plot(x, y,
marker='o',
linestyle='--',
color='blue',
label='매출')
plt.title("월별 매출")
plt.xlabel("월")
plt.ylabel("매출")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
요약
plt.plot() # 선 그래프
plt.bar() # 막대 그래프
plt.barh() # 가로 막대 그래프
plt.scatter() # 산점도
plt.hist() # 히스토그램
plt.pie() # 파이 차트
plt.title() # 제목
plt.xlabel() # x축 이름
plt.ylabel() # y축 이름
plt.legend() # 범례
plt.grid() # 격자
plt.xlim() # x축 범위
plt.ylim() # y축 범위
plt.subplot() # 여러 그래프
plt.savefig() # 이미지 저장
plt.show() # 그래프 출력