728x90
위의 그림처럼 Bar그래프를 그리는 방법을 소개하려고 해요.
지난번과 같이 한글을 사용하기 위해서는 꼭 나눔고딕체를 받아서 seabon set환경에 넣어주시면 됩니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font="NanumGothic",
rc={"axes.unicode_minus":False, 'figure.figsize':(5,5)},
style='whitegrid')
counter = df.groupby('class')['prize'].value_counts().unstack()
percentage_dist = 100 * counter.divide(counter.sum(axis = 1), axis = 0).T[['A반','B반','C반','D반']].T
ax = percentage_dist.plot.bar(stacked=True)
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1))
for p in ax.patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
ax.text(x+width/2,
y+height/2,
'{:.0f}'.format(height),
horizontalalignment='center',
verticalalignment='center')
|
cs |
만약 바그래프의 순서를 임의로 변경하고 싶다 하시면 아래 코드처럼 순서변경코드를 추가해주시면 됩니다.
아래와 같이 내용이 추가되었습니다. counter에 있는 셋을 transpose 시켜줘서 컬럼 순서를 변경하는 것입니다.
.T[['D반','C반','B반','A반']].T
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font="NanumGothic",
rc={"axes.unicode_minus":False, 'figure.figsize':(5,5)},
style='whitegrid')
counter = df.groupby('class')['prize'].value_counts().unstack()
# 만약 바그래프의 순서를 임의로 지정하고 싶다고 하면
# .T[[원하는 순서 리스트]].T로 입력해주시면 됩니다.
percentage_dist = 100 * counter.divide(counter.sum(axis = 1), axis = 0).T[['D반','C반','B반','A반']].T
ax = percentage_dist.plot.bar(stacked=True)
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1))
for p in ax.patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
ax.text(x+width/2,
y+height/2,
'{:.0f}'.format(height),
horizontalalignment='center',
verticalalignment='center')
|
cs |
만약 비중이 아니라, 각반의 학생수를 그대로 출력하고싶다면, counter라는 부분까지만 코드에 입력 해주면 됩니다.
percentage_dist는 필요가 없으니깐요.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font="NanumGothic",
rc={"axes.unicode_minus":False, 'figure.figsize':(5,5)},
style='whitegrid')
counter = df.groupby('class')['prize'].value_counts().unstack()
# 기존의 percentage_dist 막대그래프가 아닌 counter 막대그래프로
ax = counter.plot.bar(stacked=True)
plt.legend(loc='upper right', bbox_to_anchor=(1.2, 1))
for p in ax.patches:
width, height = p.get_width(), p.get_height()
x, y = p.get_xy()
ax.text(x+width/2,
y+height/2,
'{:.0f}'.format(height),
horizontalalignment='center',
verticalalignment='center')
|
cs |
위의 코드를 작성하시면 아래와 같이 간단한 그래프가 완성 됩니다.
728x90
'IT > 파이썬' 카테고리의 다른 글
[그래프] pivot_table을 활용한 heatmap 그래프 그리기 (0) | 2021.02.09 |
---|---|
Stack과 melt로 데이터 Transpose하기 (0) | 2021.02.06 |
[그래프] box-plot 그리기 (0) | 2021.01.27 |
if문과 map함수로 파생변수 만들기 (0) | 2021.01.25 |
[시간 데이터 다루기] rsub활용하여 시간차이 구하기 (0) | 2021.01.08 |