- Bar Plot은 직사각형 막대를 사용하여 데이터값을 표현하는 차트이다.
- 범주(category)에 따른 수치 값을 비교하기에 적절하다.
bar() / barh()
- bar() : 기본적인 bar plot
- barh() : horizontal bar plot
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
x = list('ABCDE')
y = np.array([1, 2, 3, 4, 5])
clist = ['blue', 'gray', 'gray', 'gray', 'red']
color = 'green'
axes[0].bar(x, y, color=clist)
axes[1].barh(x, y, color=color)
plt.show()
Multiple Bar Plot
group = student.groupby('gender')['race/ethnicity'].value_counts().sort_index()
display(group)
group
fig, axes = plt.subplots(1, 2, figsize=(10, 5), sharey=True) # sharey = y축 범위 공유
axes[0].bar(group['male'].index, group['male'], color='royalblue')
axes[1].bar(group['female'].index, group['female'], color='tomato')
plt.show()
반복문으로 특정 y값으로 y_lim을 맞춰 줄 수 도 있다.
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].bar(group['male'].index, group['male'], color='royalblue')
axes[1].bar(group['female'].index, group['female'], color='tomato')
for ax in axes:
ax.set_ylim(0, 200)
plt.show()
Stacked Bar Plot
Multiple Bar plot은 그룹 간 비교가 어렵다.
따라서 쌓아서 보면 그룹에 대한 비교가 수월하다.
fig, axes = plt.subplots(1,2, figsize=(15, 7))
group_cnt = student['race/ethnicity'].value_counts().sort_index()
axes[0].bar(group_cnt.index, group_cnt, color='darkgray')
axes[1].bar(group['male'].index, group['male'], color='royalblue')
axes[1].bar(group['female'].index, group['female'], bottom=group['male'], color='tomato') # bottom 파라미터를 사용하여 아래가 male에 관한것이 오도록함
plt.show()
그러나 남성에 대한 분포는 비교하기 쉽지만 여성에 대한 분포는 비교하기가 어려워서 Stacked Bar는 가독성이 좋지 않다.
Percentage Stacked Bar Plot
fig, ax = plt.subplots(1, 1, figsize=(12, 7))
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()
Overlapped Bar Plot
group = group.sort_index() # 다시 정렬
fig, axes = plt.subplots(2, 2, figsize=(12, 12))
axes = axes.flatten()
for idx, alpha in enumerate([1, 0.7, 0.5, 0.3]):
axes[idx].bar(group['male'].index, group['male'],
color='royalblue',
alpha=alpha)
axes[idx].bar(group['female'].index, group['female'],
color='tomato',
alpha=alpha)
axes[idx].set_title(f'Alpha = {alpha}')
for ax in axes:
ax.set_ylim(0, 200)
plt.show()
Grouped Bar Plot
fig, ax = plt.subplots(1, 1, figsize=(13, 7))
x = np.arange(len(group_list))
width=0.12 # 두께 조정
for idx, g in enumerate(edu_lv):
ax.bar(x+(-len(edu_lv)+1+2*idx)*width/2, group[g],
width=width, label=g)
ax.set_xticks(x)
ax.set_xticklabels(group_list)
ax.legend()
plt.show()