Matplotlib: Python의 데이터 시각화 라이브러리
Matplotlib은 Python에서 데이터 시각화를 위해 널리 사용되는 라이브러리입니다. 주로 2D 플롯을 생성하는 데 사용되며, 막대그래프, 선그래프, 히스토그램, 산점도 등 다양한 그래프를 그릴 수 있습니다. Matplotlib의 강력한 기능 중 하나는 사용자 지정이 가능하다는 점으로, 플롯의 모든 요소(축, 제목, 레이블, 색상 등)를 세밀하게 조정할 수 있습니다.
주요 구성 요소
- Figure: 전체 플롯이 그려지는 캔버스. 하나 이상의 Axes를 포함합니다.
- Axes: 그래프가 실제로 그려지는 영역. Figure 안에 위치합니다.
- Axis: 축 (x축과 y축)을 나타냅니다.
- Plot: 데이터를 시각화한 결과물 (선, 막대, 점 등).
기본 사용법
Matplotlib는 주로 pyplot 모듈을 사용합니다. 간단한 플롯을 만드는 과정을 단계별로 살펴보겠습니다.
설치
pip install matplotlib
예제 1: 간단한 선 그래프
import matplotlib.pyplot as plt # 데이터 준비 x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] # 그래프 생성 plt.plot(x, y, label='Prime Numbers', marker='o') # 제목 및 레이블 설정 plt.title('Simple Line Plot') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 범례 추가 plt.legend() # 그래프 출력 plt.show()
결과
위 코드를 실행하면 X축과 Y축의 값을 기반으로 선 그래프가 출력됩니다.
예제 2: 막대 그래프
# 데이터 준비 categories = ['A', 'B', 'C', 'D'] values = [5, 7, 3, 8] # 막대 그래프 생성 plt.bar(categories, values, color='skyblue') # 제목 및 레이블 설정 plt.title('Bar Chart Example') plt.xlabel('Categories') plt.ylabel('Values') # 그래프 출력 plt.show()
결과
각 카테고리에 해당하는 값들이 막대로 나타나는 그래프를 볼 수 있습니다.
예제 3: 산점도 (Scatter Plot)
import numpy as np # 데이터 준비 x = np.random.rand(50) y = np.random.rand(50) sizes = np.random.rand(50) * 100 # 산점도 생성 plt.scatter(x, y, s=sizes, alpha=0.5, color='green') # 제목 및 레이블 설정 plt.title('Scatter Plot Example') plt.xlabel('X-axis') plt.ylabel('Y-axis') # 그래프 출력 plt.show()
결과
무작위로 생성된 점들이 X-Y 좌표에 흩어져 있는 산점도가 출력됩니다.
예제 4: 히스토그램
# 데이터 준비 data = np.random.randn(1000) # 히스토그램 생성 plt.hist(data, bins=30, color='purple', alpha=0.7) # 제목 및 레이블 설정 plt.title('Histogram Example') plt.xlabel('Value') plt.ylabel('Frequency') # 그래프 출력 plt.show()
결과
1000개의 데이터가 30개의 구간으로 나뉘어 빈도 분포를 나타냅니다.
예제 5: 여러 그래프를 하나의 Figure에 추가하기
# 데이터 준비 x = np.linspace(0, 10, 100) # Figure와 Axes 생성 fig, ax = plt.subplots(2, 1, figsize=(8, 6)) # 첫 번째 그래프 ax[0].plot(x, np.sin(x), label='Sine', color='blue') ax[0].set_title('Sine Wave') ax[0].legend() # 두 번째 그래프 ax[1].plot(x, np.cos(x), label='Cosine', color='red') ax[1].set_title('Cosine Wave') ax[1].legend() # 전체 레이아웃 조정 및 출력 plt.tight_layout() plt.show()
결과
하나의 Figure에 두 개의 Axes가 포함되며, 각각 사인과 코사인 파형을 그립니다.
Matplotlib의 주요 기능
- 다양한 그래프 유형: 선 그래프, 산점도, 막대 그래프, 히스토그램, 박스 플롯 등.
- 커스터마이징: 색상, 선 스타일, 마커 스타일, 축 설정 등을 자유롭게 조정 가능.
- 서브플롯: 하나의 Figure에 여러 개의 그래프 추가.
- 3D 플롯: mpl_toolkits.mplot3d를 사용하여 3D 그래프 생성 가능.
참고 자료
import matplotlib.pyplot as plt
import numpy as np
import imageio
def create_gif(filename, frames, duration):
with imageio.get_writer(filename, mode=’I’, duration=duration) as writer:
for frame in frames:
writer.append_data(frame)
frames = []
x = np.linspace(0, 2*np.pi, 100)
for i in range(50): # 50개의 프레임 생성
y = np.sin(x + i*0.1)
plt.figure(figsize=(6, 4)) # 그래프 크기 설정 (용량에 영향)
plt.plot(x, y)
plt.title(f”Sin Wave – Frame {i+1}”)
plt.xlabel(“X”)
plt.ylabel(“Y”)
plt.ylim(-1.2, 1.2) # Y축 범위 고정 (움직임의 안정성)
# Figure를 이미지로 변환
plt.tight_layout() # 여백 최소화
fig = plt.gcf()
fig.canvas.draw()
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=’uint8′)
image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
frames.append(image)
plt.close(fig) # 메모리 관리
gif_filename = “sin_wave.gif”
gif_duration = 0.1 # 프레임 간 시간 간격 (속도 조절)
create_gif(gif_filename, frames, gif_duration)
print(f”{gif_filename} 생성 완료!”)
