learning_python: 데이터 시각화 matplotlib

MatplotLib 패키지를 이용하여 데이터 시각화하는데 활용되는 기본 파이썬 코드들


그래프 기본 그리기

import matplotlib .pyplot as plt

#기본 구성
x = [-1, 2, 3] #Series 데이터
y = [-2, 4, 8] #Series 데이터
plt.plot(x, y)
plt.show()

# 세부 요소 추가
plt.plot(x, y, color = 'm', marker = '*', label = 'school')
plt.plot(x, y, 'mo-', label = 'school') # color, marker, linestyle을 축약하여 지정
plt.legend()
plt.title('line graph')
plt.xlabel('x axis', color = 'blue', loc = 'right')
plt.ylabel('y axis', color = 'red', loc = 'top')

plt.figure(figsize=(5,3))
plt.plot(x, y, marker='o', mfc='red', ms=10, mec='blue', ls=':') #약어 사용

한글 사용하기위한 설정

import matplotlib
# matplotlib.rcParams['font.family'] = 'Malgun Gothic' # Windows
matplotlib.rcParams['font.family'] = 'AppleGothic' # Mac
matplotlib.rcParams['font.size'] = 12 # 글자 크기
matplotlib.rcParams['axes.unicode_minus'] = False # 한글 폰트 사용 시, 마이너스 깨지는 현상 보정

#사용 가능한 폰트 확인하기
import matplotlib.font_manager as fm
fm.fontManager.ttflist 
[f.name for f in fm.fontManager.ttflist]

여러 계열 포함한 그래프 그리기

days = [1, 2, 3] # 1일, 2일, 3일
az = [2, 4, 8] # (단위 : 만명) 1일부터 3일까지 아스트라제네카 접종인구
pfizer = [5, 1, 3] # 화이타
moderna = [1, 2, 5] # 모더나

plt.plot(days, az, 'mo--' ,label = 'AZ')
plt.plot(days, pfizer, 'v-',label = 'pfizer')
plt.plot(days, moderna, '*-.',label = 'moderna')
plt.legend()

그래프 그리기 활용 참조 코드

plt.figure(figsize=(5,3))
plt.bar(labels, values, color=colors, alpha=0.8, width = 0.5)
plt.ylim(170, 195)
plt.barh(labels, values, alpha=0.8)
plt.xlim(170,195)
plt.figure(figsize=(10, 7))
plt.barh(df_m.columns, -df_m.iloc[0] // 1000) # 단위 : 천 명
plt.barh(df_w.columns, df_w.iloc[0] // 1000)
plt.title('graph title')
plt.savefig('file_name.png', dpi=100)
plt.show()