범주형 데이터 그래프 만들기

스크린샷 2022-01-05 11.24.32.png

import numpy as np

df = pd.DataFrame(tips)
df.head() 

grouped = df['tip'].groupby(df['sex'])
# 성별값을 하나로 묶어  tip을 보여준다

grouped.mean() # 성별에 따른 팁의 평균
# sex
# Male      3.089618
# Female    2.833448
# Name: tip, dtype: float64
sex = dict(grouped.mean()) 
# 평균 데이터를 딕셔너리 형태로 바꿔준다. 그래야 두개 값을 빼내서 그래프로 볼 수 있어서
sex
# {'Male': 3.0896178343949043, 'Female': 2.833448275862069}
x= list(sex.keys())
x
#['Male', 'Female']
y = list(sex.values())
y
#[3.0896178343949043, 2.833448275862069]
import matplotlib.pyplot as plt

plt.bar(x=x, height=y)
plt.ylabel('tip[$]')
plt.title('Tip by Sex')

스크린샷 2022-01-05 11.26.27.png

Seaborn과 Matplotlib 활용한 간단한 방법

plt.figure(figsize=(10,6)) # 도화지 사이즈를 정합니다.
sns.barplot(data=df, x='sex', y='tip')
plt.ylim(0, 4) # y값의 범위를 정합니다.
plt.title('Tip by sex') # 그래프 제목을 정합니다.

스크린샷 2022-01-05 11.46.48.png

plt.figure(figsize=(10,6))
sns.barplot(data=df, x='day', y='tip')
plt.ylim(0, 4)
plt.title('Tip by day')

스크린샷 2022-01-05 11.49.04.png

fig = plt.figure(figsize=(10,7))

ax1 = fig.add_subplot(2,2,1)
sns.barplot(data=df, x='day', y='tip',palette="ch:.25")

ax2 = fig.add_subplot(2,2,2)
sns.barplot(data=df, x='sex', y='tip')

ax3 = fig.add_subplot(2,2,4)
sns.violinplot(data=df, x='sex', y='tip')

ax4 = fig.add_subplot(2,2,3)
sns.violinplot(data=df, x='day', y='tip',palette="ch:.25")

sns.catplot(x="day", y="tip", jitter=False, data=tips)

스크린샷 2022-01-05 11.51.04.png