본문 바로가기

Data Science/Python

matplotlib - bar chart

matplotlib는 python 시각화 라이브러리 패키지로 line plot, bar, pie, histogram, scatterplot 등 다양한 차트를 지원한다.

 

본 포스팅은 tips 데이터를 이용하여 bar chart로 시각화 한 것을 포스팅한다.

 

우선 필요한 라이브러리와 데이터를 불러온다.

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

df = pd.read_csv('/tips.csv')

df.head()

 

df.shape (244, 7)

 

tips data에서 time별 데이터의 합계를 비교한다.

 

우선 time을 기준으로 groupby하여 time별 데이터 합계를 구한다.

time_data = df.groupby('time').sum()

time_data

 

 

아래의 코드를 통해 시간 별 팁의 합계를 시각화 한 결과,

점심시간 보다 저녁 시간의 팁의 합계가 더 높은 것을 확인할 수 있다.

label = ['Dinner', 'Lunch']
index = np.arange(len(label))

plt.bar(index,
        time_data['tip'],
        color = 'slategrey');    

plt.title("Tip", fontsize=20, weight = 'bold')   # title 설정
plt.xlabel('Time', fontsize=15)    # x축 레이블 설정
plt.ylabel('Tip', fontsize=15)    # y축 레이블 설정
plt.xticks(index, label)    # x축 눈금 표시
plt.show()

 

 

 

total_bill 또한 점심시간 보다 저녁 시간의 팁의 합계가 더 높은 것을 확인할 수 있다.

그리고 width를 설정하여 bar의 폭을 줄였다.(default = 0.8)

plt.bar(index,
        time_data['total_bill'],
        color = 'lightsteelblue'
        width = 0.5);	# 막대 폭을 줄임    

plt.title("total_bill", fontsize=20, weight = 'bold')   # title 설정
plt.xlabel('Time', fontsize=15)    # x축 레이블 설정
plt.ylabel('Tip', fontsize=15)    # y축 레이블 설정
plt.xticks(index, label)    # x축 눈금 표시
plt.show()

 

 

plt.barh()는 막대 그래프를 눕혀서? 시각화한다.

 

plt.barh(index,
        time_data['total_bill'],
        color = 'lightsteelblue');    

plt.title("total_bill", fontsize=20, weight = 'bold')   # title 설정
plt.xlabel('Time', fontsize=15)    # x축 레이블 설정
plt.ylabel('Tip', fontsize=15)    # y축 레이블 설정
plt.yticks(index, label)    # x축 눈금 표시
plt.show()

 

 

 

다음은 2개의 변수를 사용하여 합계를 비교한다.

 

time(시간)과 sex(성별) 두 개의 범주형 변수의 클래스 별 tip의 합계를 비교한다.

 

아래의 코드는 데이터를 위로 쌓아 male, female의 tip을 비교한다. 

time_male = df[df['sex'] == 'Male'].groupby('time').sum()
time_female = df[df['sex'] == 'Female'].groupby('time').sum()
label = ['Dinner', 'Lunch']
n = len(df['time'].unique())
index = np.arange(n)

p1 = plt.bar(index, time_male['tip'], color='gold')
p2 = plt.bar(index, time_female['tip'], color='grey',
             bottom=time_male['tip'])

plt.title('Tips by sex / time', fontsize=20, weight = 'bold')   # title 설정
plt.xlabel('Time', fontsize=15)    # x축 레이블 설정
plt.ylabel('Tip', fontsize=15)    # y축 레이블 설정
plt.xticks(index, label)    # x축 눈금 표시
plt.legend((p1[0], p2[0]), ('Male', 'Female'), fontsize=15)
plt.show()

 

 

 

다음 코드는 데이터를 옆으로 나란히 놓고 male, female의 tip을 비교한다.

bar_width = 0.3

p1 = plt.bar(index, time_male['tip'], bar_width, color = 'gold')
p2 = plt.bar(index + bar_width, time_female['tip'], bar_width, color = 'grey')

plt.title('Tips by sex / time', fontsize=20, weight = 'bold')   # title 설정
plt.xlabel('Time', fontsize=15)    # x축 레이블 설정
plt.ylabel('Tip', fontsize=15)    # y축 레이블 설정
plt.xticks(index, label)    # x축 눈금 표시
plt.legend((p1[0], p2[0]), ('Male', 'Female'), fontsize=15)
plt.show()

 

 

끝!

'Data Science > Python' 카테고리의 다른 글

Python 결측치 처리  (0) 2021.01.14
python으로 카이제곱 검정  (0) 2021.01.06
Python으로 T-test  (0) 2021.01.05
Colab 로컬에서 파일 불러오기  (0) 2021.01.04
Python - Pandas tricks  (0) 2020.12.31