Bar Chart는 범주별 빈도를 파악할 때 사용하는 기본적인 그래프이다.
Python Seaborn 모듈의 내장 데이터인 tips 데이터 셋을 활용하여 요일별 (day) 총금액(total_bill)과 빈도를 파악해 보기로 한다.
import seaborn as sns
import matplotlib.pyplot as plt
df_tips = sns.load_dataset('tips')
df_tips
df_tips.day.unique()
Day 변수는 4 종류의 범주로 나뉘어 있다. 각 범주를 기준으로 막대그래프를 표현해 보자.
1. Seaborn 모듈을 이용한 Bar Chart
seaborn 모듈을 활용하여 요일별(day) 팁의 총금액(total_bill)을 비교해 보자.
import seaborn as sns
sns.barplot(x = 'day', y = 'total_bill', data = df_tips)
기본적인 막대 그래프 형태로 일요일(Sun)에 팁 금액이 가장 높고 금요일(Fri)에 가장 낮은 것을 볼 수 있다.
sns.barplot(x = 'day', y = 'total_bill', data = df_tips, palette='coolwarm_r')
- palette 파라미터로 색상을 원하는 대로 변경할 수 있다.
palette 파라미터에 아래와 같은 색상을 사용할 수 있다.
'Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cividis', 'cividis_r', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'flag', 'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'icefire', 'icefire_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'magma', 'magma_r', 'mako', 'mako_r', 'nipy_spectral', 'nipy_spectral_r', 'ocean', 'ocean_r', 'pink', 'pink_r', 'plasma', 'plasma_r', 'prism', 'prism_r', 'rainbow', 'rainbow_r', 'rocket', 'rocket_r', 'seismic', 'seismic_r', 'spring', 'spring_r', 'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain', 'terrain_r', 'turbo', 'turbo_r', 'twilight', 'twilight_r', 'twilight_shifted', 'twilight_shifted_r', 'viridis', 'viridis_r', 'vlag', 'vlag_r', 'winter', 'winter_r'
sns.barplot(x = 'day', y = 'total_bill',data = df_tips, palette='coolwarm_r'
,order = ['Sun', 'Sat', 'Fri', 'Thur'])
- order 파라미터를 이용해서 순서를 바꿀 수 있다. 기본 그래프와 반대로 일요일(Sun)부터 그래프가 그려졌다.
sns.barplot(x = 'total_bill', y = 'day', data = df_tips, palette='coolwarm_r')
- 수평으로 된 막대그래프를 그리려면 X와 Y 값을 반대로 입력해주면 가로로 긴 막대그래프가 생성된다.
f, ax = plt.subplots(1, 2, figsize = (15, 5))
sns.barplot(x = 'day', y = 'total_bill', data = df_tips, palette='coolwarm_r'
, hue = 'sex', ax = ax[0])
ax[0].set_title('Group Bar Chart')
sns.barplot(x = 'day', y = 'total_bill', data = df_tips, palette='coolwarm_r'
, hue = 'sex', dodge = False, ax = ax[1])
ax[1].set_title('Stacked Bar Chart')
- 성별(sex) 변수를 추가하여 그래프를 그리고 싶을 때는 hue 파라미터에 원하는 변수를 입력해 준다.
- dodge 파라미터를 False로 설정하면 오른쪽과 같이 성별 변수가 겹쳐진 형태로 그려진다. 기본 값은 True이다.
sns.countplot(x = 'day', data = df_tips)
- seaborn 모듈에서 빈도를 나타내는 막대그래프를 그리고 싶다면, counterplot 함수를 쓰는 것이 유용하다!
2. matplotlib 모듈을 이용한 Bar Chart
위에서 seaborn을 활용하여 day와 total_bill 그래프를 그려보았으니 matplotlib을 활용하여 빈도 그래프를 그려 보기로 한다.
matplotlib으로 요일별 총 팁 금액 그래프를 그리려면 아래와 같이 X와 Y자리에 원하는 변수 값을 입력하여 작성한다. (아쉬우니까..!)
f, ax = plt.subplots()
plt.bar('day', 'total_bill', data=df_tips)
ax.set_xlabel('Day')
ax.set_ylabel('Total_Bill')
다음은 Bar Chart의 기본적인 형태로 토요일(sat)에 가장 빈도가 높은 것을 볼 수 있다.
f , ax = plt.subplots()
df_tips['day'].value_counts().plot.bar(ax = ax)
ax.set_xlabel('Day')
ax.set_ylabel('Frequency')
colors = ['darksalmon', 'lightblue', 'bisque', 'lemonchiffon' ]
f , ax = plt.subplots()
df_tips['day'].value_counts().plot.bar(ax = ax, color = colors)
ax.set_xlabel('Day')
ax.set_ylabel('Frequency')
- color 파라미터를 이용하여 원하는 색상을 입력하면 다양한 색상으로 표현할 수 있다.
colors = ['darksalmon', 'lightblue', 'bisque', 'lemonchiffon' ]
f , ax = plt.subplots(1, 2, figsize = (15, 5))
df_tips['day'].value_counts().plot.bar(ax = ax[0], width = 0.3, color = colors)
ax[0].set_xlabel('Day(width = 0.3)')
ax[0].set_ylabel('Frequency')
df_tips['day'].value_counts().plot.bar(ax = ax[1], width = 1.0, color = colors)
ax[1].set_xlabel('Day(width = 1.0)')
ax[1].set_ylabel('Frequency')
- width는 막대의 넓이를 조절하는 파라미터로 0.8이 기본 값이고 작아질수록 얇은 그래프가 표현되고, 값이 커질수록 넓은 형태의 막대그래프가 표현된다.
colors = ['darksalmon', 'lightblue', 'bisque', 'lemonchiffon' ]
f , ax = plt.subplots()
df_tips['day'].value_counts().plot.barh(ax = ax, color = colors)
ax.set_xlabel('Day')
ax.set_ylabel('Frequency')
- 수평의 막대 그래프를 그리고 싶을 때는 bar 대신 barh 함수를 이용하면 옆으로 길게 나열된 형태의 막대그래프를 표현할 수 있다.
지금까지 그렸던 막대그래프에 성별(sex) 변수를 추가해 보자.
import pandas as pd
df_tips_sex = pd.crosstab(df_tips['day'], df_tips['sex'])
f, ax = plt.subplots(1, 2, figsize = (15, 5))
df_test.plot.bar(ax = ax[0], color = ['bisque', 'lightblue'])
ax[0].set_title('Group Bar Chart')
ax[0].set_ylabel('Frequency')
df_test.plot.bar(stacked =True, ax = ax[1], color = ['bisque', 'lightblue'])
ax[1].set_title('Stacked Bar Chart')
ax[1].set_ylabel('Frequency')
- 먼저 pandas 모듈의 crosstab 함수를 사용하여 요일(day)과 성별(sex)에 대한 정보만 추출하여 데이터 셋을 만들어 준다.
- 위에서 그렸던 것과 동일한 방법으로 막대그래프를 그려주고 stacked 파라미터를 True 값으로 설정하면 왼쪽의 그래프와 같이 요일별로 성별 tips 지불 빈도가 쌓여서 그래프가 그려진다.
- stacked 파라미터를 설정하지 않으면, 기본 값이 False이기 때문에 오른쪽과 같이 성별로 나란히 그래프가 그려진다.
'DIY Data Science > Visualization' 카테고리의 다른 글
[Visualization][Basic] Violin Plot(바이올린 플롯) (0) | 2021.07.14 |
---|---|
[Visualization][Basic] Pie Chart(원 그래프) (0) | 2021.07.14 |
댓글