Seaborn 범주형
Seaborn은 Matplotlib 위에 구축된 통계 시각화 라이브러리입니다. 더 적은 코드로 아름답고 정보가 풍부한 차트를 그릴 수 있습니다. 범주형 데이터 시각화는 EDA에서 가장 빈번하게 사용되는 패턴입니다.
학습 목표
- countplot으로 범주별 빈도를 시각화할 수 있다
- barplot으로 범주별 평균과 신뢰구간을 표현할 수 있다
- boxplot과 violinplot으로 범주별 분포를 비교할 수 있다
- hue 파라미터로 다차원 범주를 표현할 수 있다
왜 중요한가
범주형 피처와 수치형 타겟의 관계를 시각적으로 탐색하는 것은 EDA의 핵심입니다. 예를 들어 “성별에 따라 생존율이 다른가?”, “부서에 따라 이탈률이 다른가?” 같은 질문에 빠르게 답할 수 있습니다.
countplot — 빈도 시각화
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# 예시 데이터
np.random.seed(42)
df = pd.DataFrame({
'department': np.random.choice(['개발', '영업', '마케팅', '인사'], 200),
'gender': np.random.choice(['남', '여'], 200),
'salary': np.random.normal(4500, 800, 200),
'satisfaction': np.random.choice(['높음', '보통', '낮음'], 200)
})
# 기본 countplot
fig, ax = plt.subplots(figsize=(8, 5))
sns.countplot(data=df, x='department', ax=ax, palette='Set2')
ax.set_title('부서별 인원 분포')
plt.tight_layout()
plt.show()
# hue로 세분화
fig, ax = plt.subplots(figsize=(8, 5))
sns.countplot(data=df, x='department', hue='gender', ax=ax, palette='Set2')
ax.set_title('부서별 성별 분포')
plt.tight_layout()
plt.show()
barplot — 평균과 신뢰구간
fig, ax = plt.subplots(figsize=(8, 5))
sns.barplot(data=df, x='department', y='salary', ax=ax,
palette='Blues_d', errorbar='ci') # 95% 신뢰구간
ax.set_title('부서별 평균 연봉')
ax.set_ylabel('연봉 (만원)')
plt.tight_layout()
plt.show()
Seaborn의 barplot은 자동으로 평균과 95% 신뢰구간을 표시합니다. 오차 막대가 겹치지 않으면 두 그룹의 평균이 통계적으로 유의미하게 다를 가능성이 높습니다.
boxplot — 분포와 이상치
fig, ax = plt.subplots(figsize=(8, 5))
sns.boxplot(data=df, x='department', y='salary', hue='gender',
ax=ax, palette='Set3')
ax.set_title('부서별/성별 연봉 분포')
ax.set_ylabel('연봉 (만원)')
plt.tight_layout()
plt.show()
violinplot — 분포 밀도
fig, ax = plt.subplots(figsize=(8, 5))
sns.violinplot(data=df, x='department', y='salary',
ax=ax, palette='muted', inner='quartile')
ax.set_title('부서별 연봉 분포 (바이올린)')
ax.set_ylabel('연봉 (만원)')
plt.tight_layout()
plt.show()
stripplot과 swarmplot
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
# stripplot — 개별 데이터 포인트
sns.stripplot(data=df, x='department', y='salary', ax=axes[0],
alpha=0.5, jitter=True, palette='Set2')
axes[0].set_title('Strip Plot')
# swarmplot — 겹치지 않게 배치
sns.swarmplot(data=df.head(80), x='department', y='salary', ax=axes[1],
palette='Set2')
axes[1].set_title('Swarm Plot')
plt.tight_layout()
plt.show()
AI/ML에서의 활용
- 피처 탐색: 범주형 피처별 타겟 변수의 분포를 비교합니다
- 클래스 불균형: countplot으로 각 클래스의 샘플 수를 확인합니다
- 그룹 비교: 성별, 지역 등에 따른 성능 차이를 시각화합니다
Set2, Set3은 범주형에 적합하고, Blues_d, viridis는 순차적 데이터에 적합합니다. sns.color_palette()로 팔레트를 미리 확인할 수 있습니다.
체크리스트
다음 문서