막대의 방향에 따른 분류
fig, axes = plt.subplots(1, 2, figsize=(12, 7))
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) # Vertical
axes[1].barh(x, y, color=color) # Horizontal
axes[0].set_title("Vertical") # 제목 추가
axes[1].set_title("Horizontal")
plt.show()
Stacked 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') # 여성 그래프 추가
axes[1].set_title("Stacked Bar Chart")
for ax in axes:
ax.set_ylim(0, 350)
plt.show()
Percentage Stacked Bar Chart
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_title("Percentage Stacked Bar Plot")
# 공백 제거
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()
plt.suptitle("Overlapped Bar Plot",size=20)
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
group = student.groupby('parental level of education')['race/ethnicity'].value_counts().sort_index()
group_list = sorted(student['race/ethnicity'].unique())
edu_lv = student['parental level of education'].unique()
fig, ax = plt.subplots(1, 1, figsize=(13, 7))
x = np.arange(len(group_list))
width=0.12
plt.suptitle("Grouped Bar Plot",size=20)
# x축과 width 조정
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) # x축 이름 지정
ax.legend() # 범례추가
plt.show()
Principle of Proportion Ink(잉크량 비례 원칙)
fig, axes = plt.subplots(1, 2, figsize=(15, 7))
idx = np.arange(len(score.index))
width=0.3
for ax in axes:
ax.bar(idx-width/2, score['male'],
color='royalblue',
width=width)
ax.bar(idx+width/2, score['female'],
color='tomato',
width=width)
ax.set_xticks(idx)
ax.set_xticklabels(score.index)
axes[0].set_ylim(60, 75)
plt.show()
데이터 정렬
데이터 | 정렬 |
---|---|
시계열 | 시간 순 |
수치형 | 크기 순 |
순서형 | 범주의 순서 |
명목형 | 범주의 값에 따라 정렬 |
적절한 공간 활용
의미 | 코드 |
---|---|
X/Y 축 조정 | set_xlim(), set_ylim() |
마진 조정 | margins() |
막대 두께 조절 | width |
테두리 변 제거 | spines[spine].set_visible() |
group_cnt = student['race/ethnicity'].value_counts().sort_index()
fig = plt.figure(figsize=(15, 7))
ax_basic = fig.add_subplot(1, 2, 1)
ax = fig.add_subplot(1, 2, 2)
# 기본적인 막대 그래프
ax_basic.bar(group_cnt.index, group_cnt)
# 막대 설정
ax.bar(group_cnt.index, group_cnt,
width=0.7,
edgecolor='black',
linewidth=2,
color='royalblue'
)
# 막대 두께 조절
ax.margins(0.1, 0.1)
# 테두리 설정
for s in ['top', 'right']:
ax.spines[s].set_visible(False)
plt.show()
복잡함과 단순함
ETC