*아래 글은 부스트캠프 AI Tech 3기 안수빈 마스터님의 강의를 정리 및 재구성한 내용입니다.
Data Visualization
2-1. Matplotlib 사용법
1) Matplotlib 개요
왜 Matplotlib을 사용할까?
- Python에서 사용할 수 있는 시각화 라이브러리
- 현재 사용되고 있는 다양한 데이터 분석 및 머신러닝/딥러닝은 python에서 이루어짐
- numpy와 scipy를 베이스로 하여 다양한 라이브러리와 호환성이 좋다
- Scikit-learn, PyTorch , Tensorflow
- Pandas
- 다양한 시각화 방법론을 제공한다.
- 막대그래프
- 선그래프
- 산점도
- ETC
- matplotlib 외에도 Seaborn, Plotly, Bokeh, Altair 등의 시각화 라이브러리 존재하는데, matplotlib이 범용성이 제일 넓고 base가 되는 라이브러리라고 할 수 있다
2) Matplotlib 기본 사용법
Import library
- import 를 통해 라이브러리를 추가 하면 된다
- matplotlib은 주로 줄여서 mpl로 코드 상에서 사용한다
- version마다 되는 기능들이 다르기 때문에 최소 3.4.x 이상인지 버전을 확인하자!
import numpy as np
import matplotlib as mpl
print(f'numpy version : {np.__version__}') # version check
print(f'matplotlib version : {mpl.__version__}') # version check
- colab이나 주피터 노트북 사용 시 matplotlib 버전이 낮다면 아래와 같이 matplotlib을 업그레이드 하면 된다
!pip install --upgrade matplotlib
기본 Plot
- Figure 와 Axes : matplotlib에서 그리는 시각화는 Figure라는 큰 틀 안에 Ax라는 서브 플롯을 추가해서 만든다
fig = plt.figure() # figure 생성
plt.show()

- figure는 큰 틀이라서 1개 이상의 서브 플롯을 추가해야 시각화가 된다.
fig = plt.figure()
ax = fig.add_subplot()
plt.show()

- 그래프의 사이즈는 figsize를 이용해 figure의 크기를 조정함으로써 ax의 사이즈를 조정한다
- 가로, 세로 길이를 inch 단위로 tuple 형태로 전달한다
- 노트북 환경에서는 가로, 세로의 비율로 생각하면 된다
fig = plt.figure(figsize=(12, 7))
ax = fig.add_subplot()
plt.show()

- 2개 이상의 axes를 그려주고 싶다면 위치를 지정해 주어야 한다
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1) # figure를 세로 1 가로 2칸으로 나누고 그 중에 첫 번째
# ax = fig.add_subplot(121) 도 가능
ax2 = fig.add_subplot(1, 2, 2) # figure를 세로 1 가로 2칸으로 나누고 그 중에 두 번째
plt.show()

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
# 더 가독성을 높이려면
# ax1 = fig.add_subplot(2, 1, 1)
# ax2 = fig.add_subplot(2, 1, 2)
plt.show()

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(223)
ax3 = fig.add_subplot(224)
# 같은 내용이지만 더 가독성을 높인다면
# 다음과 같이 사용 가능
# ax1 = fig.add_subplot(2, 2, 1)
# ax2 = fig.add_subplot(2, 2, 3)
# ax3 = fig.add_subplot(2, 2, 4)
plt.show()

plt로 그래프 그리기
- 리스트 [1, 2, 3] 데이터를 ax에 그리기
fig = plt.figure()
ax = fig.add_subplot()
x = np.array([1, 2, 3])
# x = [1, 2, 3]도 가능
plt.plot()
plt.show()
- 2개를 순서대로 그리면 다음과 같이 그릴 수 있다
fig = plt.figure()
x1 = [1, 2, 3]
x2 = [3, 2, 1]
ax1 = fig.add_subplot(211)
plt.plot(x1)
ax2 = fig.add_subplot(212)
plt.plot(x2)
plt.show()

- plt로 그리는 그래프들은 순차적으로 그리기에 좋다
- 다만 절차 지향적이기 때문에 pythonic 한 코드라고 보기는 어렵다
- 좀 더 pythonic하게 구현을 하려면 ax 객체에 직접 그리면 된다
* 이렇게 matplotlib은 그릴 때 두 가지 API를 따로 지원한다
- Pyplot API : 순차적 방법
- 객체 지향(Object-Oriented) API : 그래프에서 각 객체에 대해 직접적으로 수정하는 방법
fig = plt.figure()
x1 = [1, 2, 3]
x2 = [3, 2, 1]
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot(x1)
ax2.plot(x2)
plt.show()

한 서브플롯에 여러 개 그리기
- ax에는 동시에 다양한 그래프를 그릴 수 있다
fig = plt.figure()
ax = fig.add_subplot(111)
# 3개의 그래프 동시에 그리기
ax.plot([1, 1, 1]) # 파랑
ax.plot([1, 2, 3]) # 주황
ax.plot([3, 3, 3]) # 초록
plt.show()

- 동시에 같은 종류의 그래프를 그리면 색상이 자동적으로 구분된다
- 하지만 다른 종류의 그래프를 그리면 색상이 구분되지 않기 때문에 색을 지정해 주어야 한다
fig = plt.figure()
ax = fig.add_subplot(111)
# 선그래프와 막대그래프 동시에 그리기
ax.plot([1, 2, 3], [1, 2, 3])
ax.bar([1, 2, 3], [1, 2, 3])
plt.show()

색상 지정하기
- 그래프의 색상을 직접 명시할 수 있고, 일반적으로 color 파라미터를 통해 전달한다
- 'r','g','b' 등은 기본 제공 색이라 가독성이 좋지 않고, color name은 모두 알기가 어려우므로 hex code로 찾아서 지정하는 것을 추천한다
fig = plt.figure()
ax = fig.add_subplot(111)
# 3개의 그래프 동시에 그리기
ax.plot([1, 1, 1], color='r') # 한 글자로 정하는 색상
ax.plot([2, 2, 2], color='forestgreen') # color name
ax.plot([3, 3, 3], color='#000000') # hex code (BLACK) - 가장 추천
plt.show()

텍스트 사용하기
- 정보를 추가하기 위해 텍스트를 사용할 수 있다
- ax에 plot할 때 label을 지정하면 시각화에서는 드러나지 않지만, 범례(legend)를 추가하면 표시가 된다
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
plt.show()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.legend()
plt.show()

- ax의 제목을 추가할 수도 있다
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.legend()
plt.show()

- figure의 제목(title)은 suptitle을 통해 지정할 수 있다 (sup은 super, 즉 최상위 객체를 의미한다)
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.set_title('ax1')
ax2.set_title('ax2')
fig.suptitle('fig') # sup == super
plt.show()

* ax 에서 특정 데이터를 변경하는 경우에는 .set_{} () 형태의 메서드가 많다
* set으로 세팅하는 정보들은 반대로 해당 정보를 받아오는 경우에는 .ge_{} () 형태의 메서드를 사용한다
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.legend()
print(ax.get_title()) # title 정보 받아오기
plt.show()

- 축은 ticks와 ticklabels로 구분된다
- ticks는 축에 적히는 수 위치를 지정한다
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.set_xticks([0, 1, 2]) # 축에 적히는 수 지정
ax.legend()
plt.show()

- ticklabels는 축에 적히는 텍스트를 수정한다
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(['zero', 'one', 'two']) # 축에 적히는 텍스트 수정
ax.legend()
plt.show()

- 일반적인 텍스트 추가 방식은 두 가지가 있다 : text, annotation
* text
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(['zero', 'one', 'two'])
ax.text(x=1, y=2, s='This is Text') # (1, 2) 좌표에 텍스트 적기
ax.legend()
plt.show()

* annotation
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(['zero', 'one', 'two'])
ax.annotate(text='This is Annotate', xy=(1, 2)) # 좌표에 annotation 추가
ax.legend()
plt.show()

* annotation은 화살표 등을 추가할 수 있다
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 1, 1], label='1')
ax.plot([2, 2, 2], label='2')
ax.plot([3, 3, 3], label='3')
ax.set_title('Basic Plot')
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(['zero', 'one', 'two'])
ax.annotate(text='This is Annotate', xy=(1, 2),
xytext=(1.2, 2.2),
arrowprops=dict(facecolor='black'), # 화살표 추가
)
ax.legend()
plt.show()

'부스트캠프 AI Tech 공부 기록 > Data Visualization' 카테고리의 다른 글
| [Data Viz] Text (feat.Matplotlib) (0) | 2022.02.06 |
|---|---|
| [Data Viz] Matplotlib 사용법 : Scatter Plot (0) | 2022.02.05 |
| [Data Viz] Matplotlib 사용법 : Line Plot (0) | 2022.02.05 |
| [Data Viz] Matplotlib 사용법 : Bar Plot (0) | 2022.02.04 |
| [Data Viz] 데이터 시각화 개요 (0) | 2022.02.03 |