본문 바로가기

Data Science/Data Visualization

[01. Bar Chart] 004. Percentage Stacked Bar Chart

728x90

누적된 막대그래프를 백분율화 시킨 차트이다. 각 항목의 수량보다는 비율이 더 중요할 때 사용한다.

 

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import seaborn as sns

if __name__ == '__main__':
    sns.set_style(style="whitegrid")
    tips = sns.load_dataset("tips")
    total = tips.groupby('day')['total_bill'].sum().reset_index()
    smoker = tips[tips['smoker'] == 'Yes'].groupby('day')['total_bill'].sum().reset_index()
    smoker['total_bill'] = [i / j * 100 for i, j in zip(smoker['total_bill'], total['total_bill'])]
    total['total_bill'] = [i / j * 100 for i, j in zip(total['total_bill'], total['total_bill'])]
    print(total.head())
    print(smoker.head())

    bar1 = sns.barplot(x="day", y="total_bill", data=total, color='darkblue')
    bar2 = sns.barplot(x="day", y="total_bill", data=smoker, color='lightblue')
    top_bar = mpatches.Patch(color='darkblue', label='smoker = No')
    bottom_bar = mpatches.Patch(color='lightblue', label='smoker = Yes')
    plt.legend(handles=[top_bar, bottom_bar])
    plt.show()


결과 값
    day  total_bill
0  Thur       100.0
1   Fri       100.0
2   Sat       100.0
3   Sun       100.0
    day  total_bill
0  Thur   29.757464
1   Fri   77.390450
2   Sat   50.248538
3   Sun   28.164409

 

728x90