Matplotlib을 이용한 막대 그래프 만들기 (bar plot) | 누적 막대 그래프, 비율, 묶은 막대 그래프
Barplot
직사각형 막대를 이용해 데이터 값을 표현하는 대표적인 차트입니다. 범주에 따른 수치 값을 비교할 때 적합한 방법으로 많이 사용합니다. mataplotlib.pyplot에서는 .bar (일반적인 수직형 막대) / .barh (수평형 막대, 범주가 많을 때 아래로 내리면서 사용) 크게 두가지 방법으로 사용할 수 있습니다.
먼제 seaborn에 내장되어 있는 titanic 데이터를 불러와 데이터를 준비하겠습니다.
# Library
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
titanic = sns.load_dataset('titanic')
print(titanic.head())
실습 1. 막대그래프 기본값에서 변경
막대그래프를 효과적으로 보여주기 위해 아래 항목들을 조정할 수 있습니다.
- .set_xlim(), .set_ylim() : 축의 범위 조절
- width = : 막대 너비 조절
- color = : 막대 색 변화
- .spines[spine].set_visible() : spine(top, right, left, bottom)의 차트의 테두리
group_cnt = titanic['class'].value_counts().sort_index()
fig, ax = plt.subplots()
ax.bar(group_cnt.index,
group_cnt,
width=0.7, # 너비 조절
edgecolor='black', # 테두리 색
linewidth=2,
color='royalblue')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()
실습 2. 누적 막대 그래프 (Stacked Barplot)
여러 개의 그룹을 쌓아서 표시하는 누적 막대 그래프는 한꺼번에 다양한 카테고리를 살펴볼 수 있는 장점이 있습니다. 위에서 생성한 타이타닉 데이터셋에 bar로 먼저 바닥에 만들 그래프를 생성하고, 그 위에 bottom 파라미터에 바닥에 있을 데이터를 지정해 얹는 방식으로 진행합니다. 만약 barh를 사용하는 경우 lef 파라미터를 사용합니다.
# Stacked Barplot
fig, ax = plt.subplots()
group = titanic.groupby(['sex', 'class']).size()
group_cnt = titanic['class'].value_counts().sort_index()
ax.bar(group['male'].index, group['male'], color='royalblue')
ax.bar(group['female'].index, group['female'], bottom=group['male'], color='tomato')
plt.show()
실습 3. 100% 기준 누적 막대 그래프
전체 비율을 나타내기 위해서는 100 % 기준 누적 막대 그래프(Percentage stacked bar chart)를 활용해주는 것도 좋습니다. 전체 비율을 계산하기 위한 total 값 계산만 추가해서 만들어주면 됩니다.
# Percentage Stacked Barplot
fig, ax = plt.subplots()
group = group.sort_index(ascending=False)
total=group['male']+group['female']
ax.barh(group['male'].index, group['male']/total,
color='royalblue')
ax.barh(group['female'].index, group['female']/total,
left=group['male']/total,
color='tomato')
ax.set_xlim(0, 1)
for s in ['top', 'bottom', 'left', 'right']:
ax.spines[s].set_visible(False)
plt.show()
실습 4. 묶은 세로 막대형 (Grouped bar plot)
matplotlib으로 구현이 쉽지는 않지만, 여러 유형의 카테고리를 묶어서 같이 표현하는 방법도 가능합니다. 너비만큼 x축으로 평행이동 시키면서 막대 그래프를 지속적으로 그려주는 형태로 그려줄 수 있습니다. 아래는 matplolib에서 소개하고 있는 예시입니다. [1]
# data from https://allisonhorst.github.io/palmerpenguins/
import matplotlib.pyplot as plt
import numpy as np
species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
'Bill Depth': (18.35, 18.43, 14.98),
'Bill Length': (38.79, 48.83, 47.50),
'Flipper Length': (189.95, 195.82, 217.19),
}
x = np.arange(len(species)) # the label locations
width = 0.25 # the width of the bars
multiplier = 0
fig, ax = plt.subplots(layout='constrained')
for attribute, measurement in penguin_means.items():
offset = width * multiplier
rects = ax.bar(x + offset, # x축 평행 이동
measurement,
width,
label=attribute) # 레이블 지정
ax.bar_label(rects, padding=3)
multiplier += 1
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)
plt.show()
참고자료
[1] https://matplotlib.org/stable/gallery/lines_bars_and_markers/barchart.html