함께하는 데이터 분석

[Python] Matplotlib 누적 막대그래프 본문

데이터분석 공부/Python

[Python] Matplotlib 누적 막대그래프

JEONGHEON 2022. 4. 5. 18:47

오늘은 matplotlib을 활용하여

 

누적 막대그래프를 그려보도록 하겠습니다.

 

데이터는 저번과 같이

 

학년도 별 수능 과학탐구 응시자 수 데이터를 이용해보겠습니다.

 

 

라이브러리 불러오기

import matplotlib.pyplot as plt
import pandas as pd

plt.rc('font', family = 'AppleGothic') # mac 
# plt.rc('font', family = 'Malgun Gothic') # window
plt.rc('font', size = 12)
plt.rc('axes', unicode_minus = False) # -표시 오류 잡아줌

 

 

데이터 생성

# 년도
year = [2018, 2019, 2020, 2021, 2022]

# 만명 단위
physics = [6.2,6.3 ,6.0 ,5.9 ,6.8] 
chemistry = [10.6,9.4 ,8.0 ,8.0 ,8.0]
life = [16.1,16.3 ,13.9 ,13.1 ,14.7]
earth = [16.7,17.7 ,16.1 ,13.0 ,14.9]

이전까지는 리스트 형태로 이용했었는데

 

이번에는 DataFrame으로 만들어주기 위해

 

딕셔너리 형태로 만들어주겠습니다.

 

science = {
    "year" : year,
    "physics" : physics,
    "chemistry" : chemistry,
    "life" : life,
    "earth" : earth
}

 

sci = pd.DataFrame(science)
sci

pandas를 이용하여 딕셔너리를 DataFrame형태로 변경해주었습니다.

 

 

막대그래프 그리기

plt.figure(figsize = (10, 5))
plt.bar(sci['year'], sci['earth'])
plt.show()

x축에 학년도를 y축에 지구과학 응시자 수를 넣어서

 

단일 막대그래프를 그렸습니다.

 

이제는 생명과학 응시자 수를 누적이 아닌 겹쳐서 그려볼까요?

 

plt.figure(figsize = (10, 5))
plt.bar(sci['year'], sci['earth'])
plt.bar(sci['year'], sci['life'])
plt.show()

이렇게 plt.bar를 이중으로 사용하면

 

막대그래프가 겹쳐서 그려지게 됩니다.

 

주황색 막대그래프가 생명과학 응시자 수를 나타냅니다.

 

이렇게 그리면 2021학년도 같은 경우에는

 

지구과학 응시자 수를 알기가 힘든 문제가 발생합니다.

 

따라서 지구과학 응시자 수와 생명과학 응시자 수를 누적으로 그려보겠습니다.

 

 

누적 막대그래프 그리기

plt.figure(figsize = (10, 5))
plt.bar(sci['year'], sci['earth'])
plt.bar(sci['year'], sci['life'], bottom = sci['earth'])
plt.show()

생명과학 응시자 수가 들어간 plt.bar에

 

bottom인자에 지구과학을 추가하면

 

위와 같이 지구과학 응시자 수가 아래로 깔리고

 

생명과학 응시자 수가 위로 올라간 누적 막대그래프가 생성됩니다.

 

이번에는 화학 응시자 수를 추가하겠습니다.

 

plt.figure(figsize = (10, 5))
plt.bar(sci['year'], sci['earth'])
plt.bar(sci['year'], sci['life'], bottom = sci['earth'])
plt.bar(sci['year'], sci['chemistry'], bottom = sci['earth'] + sci['life'])
plt.show()

역시 마지막인 화학 plt.bar에

 

sci['earth'] + sci['life']를 bottom에 넣어줬습니다.

 

마지막 과학탐구 과목인 물리까지 누적시켜주겠습니다.

 

plt.figure(figsize = (10, 5))
plt.bar(sci['year'], sci['earth'])
plt.bar(sci['year'], sci['life'], bottom = sci['earth'])
plt.bar(sci['year'], sci['chemistry'], bottom = sci['earth'] + sci['life'])
plt.bar(sci['year'], sci['physics'], bottom = sci['earth'] + sci['life'] + sci['chemistry'])
plt.show()

이제 앞서 활용해보았던 범례와 x축, y축, title을 달아주면서 마무리하겠습니다.

 

plt.figure(figsize = (10, 5))
plt.title('학년도 기준 수능 과학탐구 응시자 수')
plt.xlabel('학년도')
plt.ylabel('응시자 수(단위 : 만명)')
plt.bar(sci['year'], sci['earth'], label = '지구과학')
plt.bar(sci['year'], sci['life'], bottom = sci['earth'], label = '생명과학')
plt.bar(sci['year'], sci['chemistry'], bottom = sci['earth'] + sci['life'], label = '화학')
plt.bar(sci['year'], sci['physics'], bottom = sci['earth'] + sci['life'] + sci['chemistry'], label = '물리학')
plt.legend(ncol = 4)
plt.show()

이상으로 누적 막대그래프를 마무리하겠습니다.

 

다음에는 다중 막대그래프로 찾아뵙겠습니다!