[Seaborn] 1. scatterplot
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=(10, 6))
sns.scatterplot(data=df, x='국어', y='수학')
plt.title('국어와 수학 성적의 산점도')
plt.show()
- data에 데이터프레임, x랑 y에 각각 컬럼 삽입
2. 그룹화
plt.figure(figsize=(10, 6))
sns.scatterplot(data=df, x='국어', y='수학', hue='성별')
plt.title('성별에 따른 국어/수학 성적 산점도')
plt.show()
- 성별에 따른 색상 분류
3. 스타일링
plt.figure(figsize=(10, 6))
sns.scatterplot(data=df, x='국어', y='수학',
hue='성별', style='성별', size=10)
plt.title('성별에 따른 국어/수학 성적 산점도 (마커 스타일 적용)')
plt.show()
- 성별에 따른 style 분류
- size로 스타일의 크기 지정이 가능하다.
4. 투명도, 색상 팔레트
plt.figure(figsize=(10, 6))
sns.scatterplot(data=df, x='국어', y='수학',
hue='성별',
alpha=0.6, # 투명도
palette='Set2') # 컬러 팔레트
plt.title('성별에 따른 국어/수학 성적 산점도 (커스텀 색상)')
plt.show()
5. 크기범위 추가
plt.figure(figsize=(12, 8))
sns.scatterplot(data=df, x='국어', y='수학',
hue='반', size='영어',
sizes=(20, 200), # 크기 범위
palette='deep')
plt.title('반별 국어/수학 성적 산점도 (영어 성적에 따른 크기 변화)')
plt.show()
6. 상세 커스터마이징
# 스타일 초기화
sns.set_style("white")
plt.rcParams["font.family"] = "D2coding"
plt.figure(figsize=(12, 8))
# 산점도 생성
sns.scatterplot(data=df, x='국어', y='수학',
hue='성별', style='반',
size='영어',
sizes=(50, 250),
palette='husl',
alpha=0.7)
# 제목과 레이블 설정
plt.title('종합 성적 분석 산점도', pad=15, size=14)
plt.xlabel('국어 성적', size=12)
plt.ylabel('수학 성적', size=12)
# 범례 위치 조정
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
# 그리드 추가
plt.grid(True, linestyle='--', alpha=0.7)
# 여백 조정
plt.tight_layout()
plt.show()
정리
sns.scatterplot(
# 기본 데이터 설정데이터프레임 / X축 / Y축
data=df, x='col1', y='col2',
# 그룹화 및 스타일링 : 색상 구분 / 마커 구분 / 투명도 / 팔레트
# 색상 팔레트 ['deep', 'muted', 'pastel', 'bright', 'dark', 'Set1', 'Set2', 'Set3', 'husl', 'hls', 'Paired', 'Spectral', 'coolwarm', 'RdYlBu']
hue='col3', style='col4', alpha=0.7, palette='husl',
# 마커 설정 : 마커모양 / 마커 크기 / 마커 크기범위
markers=['o', 's', 'D', '^'], size='col5', sizes=(a,b)
# 범례 설정 ['brief', 'full']
legend=False
)
- 스니펫으로 설정해서 불러올 수 있게 설정하면 끝
"Seaborn Scatterplot Template": {
"prefix": "sns_scatter",
"body": [
"sns.scatterplot(",
" # 기본 데이터 설정: 데이터프레임 / X축 / Y축",
" data=${1:df}, x='${2:col1}', y='${3:col2}',",
"",
" # 그룹화 및 스타일링: 색상 구분 / 마커 구분 / 투명도 / 팔레트",
" # 색상 팔레트 ['deep', 'muted', 'pastel', 'bright', 'dark', 'Set1', 'Set2', 'Set3', 'husl', 'hls', 'Paired', 'Spectral', 'coolwarm', 'RdYlBu']",
" hue='${4:col3}', style='${5:col4}', alpha=${6:0.7}, palette='${7:muted}',",
"",
" # 마커 설정: 마커모양 / 마커 크기 / 마커 크기범위",
" markers=['o', 's', 'D', '^'], size='${8:col5}', sizes=(${9:50}, ${10:200}),",
"",
" # 범례 설정 ['brief', 'full', False]",
" legend=${11:'brief'}",
")"
],
"description": "Create a Seaborn scatterplot 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] 3. boxplot (0) | 2024.11.15 |
[Seaborn] 2. histplot (0) | 2024.11.15 |
댓글