[Seaborn] 9. countplot
seaborn countplot
사용할 데이터
import numpy as np
import pandas as pd
n = 1000
# 기본 능력치 생성 (학생들의 전반적인 학습 능력)
base_ability = np.random.normal(0, 1, size=n)
physical_ability = np.random.normal(0, 1, size=n) # 체육 능력 추가
# 과목별 점수 생성
국어 = 75 + 10 * (0.7 * base_ability + 0.3 * np.random.normal(0, 1, size=n))
영어 = 72 + 12 * (0.6 * base_ability + 0.4 * np.random.normal(0, 1, size=n))
수학 = 70 + 15 * (0.8 * base_ability + 0.2 * np.random.normal(0, 1, size=n))
# 체육은 수학과 반비례하도록 -base_ability 사용
체육 = 80 + 8 * (-0.6 * base_ability + 0.8 * physical_ability + 0.2 * np.random.normal(0, 1, size=n))
# 점수 범위 조정 및 반올림
data = {
'국어': np.round(np.clip(국어, 50, 100), 1),
'영어': np.round(np.clip(영어, 50, 100), 1),
'수학': np.round(np.clip(수학, 50, 100), 1),
'체육': np.round(np.clip(체육, 50, 100), 1),
'성별': np.random.choice(['남', '여'], size=n),
'반': np.random.choice([f'{i}반' for i in range(1,10)], size=n)
}
df = pd.DataFrame(data)
1. pairplot 기본
sns.countplot(
data=df
)
- 범주형 컬럼에 있는 데이터 수를 보여준다
2. 그룹화
sns.countplot(data=df, x='반')
- x축에 범주형 변수 추가하기
3. 색상
sns.countplot(data=df, x='반', hue='성별')
- hue에 범주형 하나 더 추가하면, grouped된 x별로 count된다.
4. 상세 커스터마이징
sns.countplot(
# 기본 데이터 설정: 데이터프레임 / X축(범주) / 색상구분 / 정렬순서 (df['반'].value_counts().index)
data=df, x='반', hue='성별', order=df['반'].value_counts().index,
# 스타일 설정: 팔레트 / 채도
palette='muted', saturation=0.7,
# 막대 설정: 너비 / 테두리색 / 테두리두께
width=0.8, edgecolor='black', linewidth=1
)
# 막대 위에 숫자 표시
for p in plt.gca().patches:
plt.gca().annotate(f'{int(p.get_height())}',
(p.get_x() + p.get_width()/2, p.get_height()),
ha='center', va='bottom')
plt.title('반별 성별 학생 수', pad=15)
- 범주형 순서를 부여하고싶으면 order에 list 전달하기
정리
sns.countplot(
# 기본 데이터 설정: 데이터프레임 / X축(범주) / 색상구분 / 정렬순서
data=df, x='col1', hue='col2', order=[col1 순서리스트],
# 스타일 설정: 팔레트 / 채도
palette='muted', saturation=0.7,
# 막대 설정: 너비 / 테두리색 / 테두리두께
width=0.8, edgecolor='black', linewidth=1
)
스니펫
{
"Seaborn Countplot Template": {
"prefix": "sns_count",
"body": [
"sns.countplot(",
" # 기본 데이터 설정: 데이터프레임 / X축 / 색상구분 / 정렬순서",
" data=${1:df}, x='${2:col1}', hue='${3:col2}', order=${4:col1_list},",
"",
" # 스타일 설정: 팔레트 / 채도",
" palette='${5:muted}', saturation=${6:0.7},",
"",
" # 막대 설정: 너비 / 테두리색 / 테두리두께",
" width=${7:0.8}, edgecolor='${8:black}', linewidth=${9:1}",
")"
],
"description": "Create a Seaborn countplot with common parameters"
}
}
'Data Visualization > Seaborn' 카테고리의 다른 글
[Seaborn] 12. lineplot (0) | 2024.11.15 |
---|---|
[Seaborn] 11. swarmpplot (0) | 2024.11.15 |
[Seaborn] 10. stripplot (0) | 2024.11.15 |
[Seaborn] 8. pairplot (0) | 2024.11.15 |
[Seaborn] 7. jointplot (0) | 2024.11.15 |
[Seaborn] 6. heatmap (0) | 2024.11.15 |
[Seaborn] 5. barplot (0) | 2024.11.15 |
댓글