데이터 분석/matplotlib

matplotlib 그래프 그리기 - 꺾은선 그래프

haloaround 2022. 8. 15. 23:16

 


matplotlib 에서 제어가능한 여러 요소들을 해부해본다!

matplotlib: 파이썬에서 차트나 플롯으로 데이터를 시각화하기 위한 모듈
- 그래프 종류: 산점도, 꺾은선 그래프, 막대  그래프, 히스토그램, 박스 플롯

 


 

0. font 설치

!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf

출처: https://teddylee777.github.io/colab/colab-korean

 

 

1. 데이터 시각화의 대상, DataFrame 불러오기

import pandas as pd
df = pd.read_csv('시간대별_상품판매량.csv', engine='python', encoding='cp949')
df.head()

 

 

2. matplotlib, numpy Import

library 를 import 하고, pyplot 에 대한 파라미터를 세팅한다. 

from matplotlib import pyplot as plt 
import numpy as np

%matplotlib inline 
# 그래프를 셀에 출력

plt.rcParams['font.family'] = 'NanumBarunGothic'
plt.rcParams['font.size'] = 20
plt.rcParams['figure.figsize'] = (30, 10)

 

 

3. 그래프 그리기

a. pyplot 을 통해 그래프 그리기

plt.title('날짜별 상품 판매량')
plt.xlabel('날짜')
plt.ylabel('판매량(개수)')

xtick_range = np.cumsum([0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30])
xtick_label = df['날짜'].loc[xtick_range]
plt.xticks(xtick_range, xtick_label)

plt.plot(df['날짜'], df['상품1'], label='상품1', color='b')
plt.plot(df['날짜'], df['상품2'], label='상품2', color='g')
plt.plot(df['날짜'], df['상품3'], label='상품3', color='r')

plt.legend()

 

b. df.plot() 을 통해 그래프 그리기

df.plot(kind='line', x='날짜', y=['상품1', '상품2', '상품3'])

xtick_range = np.cumsum([0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30])
xtick_label = df['날짜'].loc[xtick_range]
plt.xticks(xtick_range, xtick_label)

plt.title('날짜별 상품 판매량')
plt.xlabel('날짜')
plt.ylabel('판매량(개수)')

 

c. df 기준 월 단위로 그래프 그리기

x축: index (월) 

y축: columns [['상품1', '상품2', '상품3']]

df.groupby('월')[['상품1', '상품2', '상품3']].sum().plot(kind='line')

plt.xticks(range(12), [str(i+1)+'월' for i in range(12)])

plt.title('날짜별 상품 판매량')
plt.xlabel('날짜')
plt.ylabel('판매량(개수)')

 

파편화된 것보다 요약되었을 때 가시성이 높아졌다!

 

 

4. matplotlib, Parts of Figure

출처: https://matplotlib.org/stable/tutorials/introductory/usage.html