[Seaborn] 3. boxplot
seaborn 박스플롯
사용할 데이터
from sqlalchemy import create_engine
import numpy as np
import pandas as pd
n = 300
data = {
'국어': np.round(np.random.normal(75, 10, size=n).clip(50, 100), 1),
'영어': np.round(np.random.normal(72, 12, size=n).clip(50, 100), 1),
'수학': np.round(np.random.normal(70, 15, size=n).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. 기본 박스플롯
plt.figure(figsize=(12, 6))
sns.boxplot(
data=df, x='반', y='국어',
)
- data에 데이터프레임, x,y에 컬럼 각각 삽입
2. 그룹화
plt.figure(figsize=(12,6))
sns.boxplot(
data=df, x='반', y='국어',
hue='성별', palette='muted',
width=0.8, linewidth=1.5, # 박스 스타일링: 박스너비 / 테두리색상 / 테두리두께
whis=1.5, # IQR의 1.5배
fliersize=5 # 이상치 점 크기
)
- hue랑 palette는 다른 플롯과 비슷하다.
3. 박스 스타일링
plt.figure(figsize=(12, 6))
sns.boxplot(
data=df, x='반', y='국어',
# 그룹화 및 스타일링: 색상 구분 / 투명도 / 팔레트
hue='성별', palette='muted',
# 박스 스타일링: 박스너비 / 테두리두께
width=0.5, linewidth=2.5,
)
4. 이상치 스타일링
plt.figure(figsize=(12, 6))
sns.boxplot(
# 기본 데이터 설정
data=df, x='반', y='국어',
# 그룹화 및 스타일링: 색상 구분 / 팔레트 / 채도
hue='성별', palette='muted', saturation=0.7,
# 박스 스타일링: 박스너비 / 테두리두께
width=0.5, linewidth=2.5,
# 이상치 설정: IQR 범위 / 이상치 점 크기 / 점 스타일
whis=1.5, fliersize=10,
# 각 요소 스타일 커스터마이징
medianprops={'color': 'black', 'linewidth': 2}, # 중앙값 선
whiskerprops={'linewidth': 1.5, 'linestyle': '--'},# 수염 선
capprops={'linewidth': 2.5}, # 수염 끝 선
boxprops={'linewidth': 2}, # 박스 테두리
flierprops={'marker': 'o', 'markerfacecolor': 'gray'} # 이상치 점
)
5. 상세 커스터마이징
plt.figure(figsize=(12, 6))
plt.style.use('seaborn-v0_8') # 또는 'seaborn-darkgrid', 'seaborn-whitegrid' 등
plt.rcParams["font.family"] = "D2coding"
sns.boxplot(
# 기본 데이터 설정
data=df, x='반', y='국어',
# 그룹화 및 스타일링: 색상 구분 / 팔레트 / 채도
hue='성별', palette='muted', saturation=0.7,
# 박스 스타일링: 박스너비 / 테두리두께
width=0.5, linewidth=2.5,
# 이상치 설정: IQR 범위 / 이상치 점 크기 / 점 스타일
whis=1.5, fliersize=10,
# 각 요소 스타일 커스터마이징
medianprops={'color': 'red', 'linewidth': 2}, # 중앙값 선
whiskerprops={'linewidth': 1.5, 'linestyle': '--'},# 수염 선
capprops={'linewidth': 1.5}, # 수염 끝 선
boxprops={'linewidth': 2}, # 박스 테두리
flierprops={'marker': 'o', 'markerfacecolor': 'gray'} # 이상치 점
)
# 제목 및 레이블 설정
plt.title('반별 국어 점수 분포', pad=15, size=14, weight='bold')
plt.xlabel('반', size=12)
plt.ylabel('국어 점수', size=12)
# 범례 설정
plt.legend(
title='성별',
title_fontsize=10,
fontsize=9,
bbox_to_anchor=(1.02, 1),
loc='upper left'
)
# 격자 설정
plt.grid(True, axis='y', linestyle='--', alpha=0.3)
plt.tight_layout()
정리
sns.boxplot(
# 기본 데이터 설정: 데이터프레임 / X축 / Y축
data=df, x='col1', y='col2',
# 그룹화 및 스타일링: 색상 구분 / 팔레트 / 채도
hue='col3', palette='muted', saturation=0.7,
# 박스 스타일링: 박스너비 / 테두리두께
width=0.5, linewidth=2.5,
# 이상치 설정: IQR 범위 / 이상치 점 크기
whis=1.5, fliersize=10,
# 요소별 스타일링: 중앙값 / 수염 / 수염끝 / 박스 / 이상치
medianprops={'color': 'black', 'linewidth': 2}, # 중앙값 선 스타일
whiskerprops={'linewidth': 1.5, 'linestyle': '--'}, # 수염 선 스타일
capprops={'linewidth': 2.5}, # 수염 끝 선 스타일
boxprops={'linewidth': 2}, # 박스 테두리 스타일
flierprops={'marker': 'o', 'markerfacecolor': 'gray'} # 이상치 점 스타일
)
- 스니펫으로 설정해서 불러올 수 있게 설정하면 끝
{
"Seaborn Boxplot Template": {
"prefix": "sns_box",
"body": [
"sns.boxplot(",
" # 기본 데이터 설정: 데이터프레임 / X축(범주) / Y축(수치)",
" data=${1:df}, x='${2:col1}', y='${3:col2}',",
"",
" # 그룹화 및 스타일링: 색상 구분 / 팔레트 / 채도",
" hue='${4:col3}', palette='${5:muted}', saturation=${6:0.7},",
"",
" # 박스 스타일링: 박스너비 / 테두리두께",
" width=${7:0.5}, linewidth=${8:2.5},",
"",
" # 이상치 설정: IQR 범위 / 이상치 점 크기",
" whis=${9:1.5}, fliersize=${10:10},",
"",
" # 요소별 스타일링: 중앙값 / 수염 / 수염끝 / 박스 / 이상치",
" medianprops={'color': '${11:black}', 'linewidth': ${12:2}},",
" whiskerprops={'linewidth': ${13:1.5}, 'linestyle': '${14:--}'},",
" capprops={'linewidth': ${15:2.5}},",
" boxprops={'linewidth': ${16:2}},",
" flierprops={'marker': '${17:o}', 'markerfacecolor': '${18:gray}'}",
")"
],
"description": "Create a Seaborn boxplot with common parameters"
}
}
'Data Visualization > Seaborn' 카테고리의 다른 글
[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 |
[Seaborn] 4. violin plot (0) | 2024.11.15 |
[Seaborn] 2. histplot (0) | 2024.11.15 |
[Seaborn] 1. scatterplot (0) | 2024.11.14 |
댓글