본문 바로가기
Data Visualization/Seaborn

[Seaborn] 6. heatmap

by 베짱이28호 2024. 11. 15.

[Seaborn] 6. heatmap

seaborn 히트맵


사용할 데이터

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. 히트맵 기본

plt.figure(figsize=(10, 8))
corr = df[['국어', '영어', '수학', '체육']].corr()
sns.heatmap(
    data=corr,
)
plt.title('과목간 상관관계', pad=15)
  • 데이터만 넣으면 아무것도 안보인다.


2. 컬러맵, 범위 지정

plt.figure(figsize=(10, 8))
corr = df[['국어', '영어', '수학', '체육']].corr()
sns.heatmap(
    data=corr,
    cmap='RdBu_r', cbar=True,
    vmin=-1, vmax=1,
)
plt.title('과목간 상관관계', pad=15)
    • 컬러맵을 지정해주고, 우측에 컬러바를 추가한다.
    • vmin vmax로 범위를 직접 지정할 수 있다.
    • 지정하지 않으면, 자동으로 범위 내에서 최대 최소를 찾아서 매핑한다.


3. 스타일링

plt.figure(figsize=(10, 8))
corr = df[['국어', '영어', '수학', '체육']].corr()

sns.heatmap(
    # 데이터 설정
    data=corr,
    
    # 색상 설정: 컬러맵 / 컬러바 / 최소범위 / 최대범위 / 투명도
    cmap='RdBu_r', cbar=True, vmin=-1, vmax=1, alpha=0.8,
    
    # 데이터값 표시: 소수점 자리수
    annot=True, fmt='.2f',
    
    # 선 설정: 선 너비 / 선 색상
    linewidths=1, linecolor='white',
)

plt.title('과목간 상관관계', pad=15)
        • 막대 그래프 두께, 테두리 등 설정이 가능하다.


4. 상세 커스터마이징

# 스타일 설정
plt.style.use('seaborn-v0_8')
plt.rcParams["font.family"] = "D2coding"
plt.figure(figsize=(10, 8))

# 상관계수 계산
corr = df[['국어', '영어', '수학', '체육']].corr()

# 히트맵 생성
sns.heatmap(
    # 데이터 설정
    data=corr,
    
    # 색상 설정: 컬러맵 / 컬러바 / 최소범위 / 최대범위 / 투명도
    cmap='coolwarm', cbar=True, vmin=-1, vmax=1, alpha=0.7,
    
    # 데이터값 표시: 소수점 자리수 / 글자크기 / 글자색
    annot=True, fmt='.2f', annot_kws={'size':12, 'weight':'bold'},
    
    # 선 설정: 선 너비 / 선 색상
    linewidths=2, linecolor='white',
    
    # 기타 설정: 정사각형 / 마스크
    square=True,  mask=np.triu(corr) # 으로 상단만 표시 가능
)

plt.title('과목별 상관관계 분석', pad=15, size=14, weight='bold')
  • mask를 생성해서 triangle upper / lower를 만들어서 주대각 위 아래를 필터링할 수 있다.


정리

sns.heatmap(
    # 데이터 설정
    data=corr,
    
    # 색상 설정: 컬러맵 / 컬러바 / 최소범위 / 최대범위 / 투명도 / 컬러바 중심점 
    # cmap: 'RdBu_r', 'coolwarm', 'YlOrRd', 'viridis', 'magma'
    cmap='RdBu_r', cbar=True, vmin=-1, vmax=1, alpha=0.8, center=0,
    
    # 데이터값 표시: 소수점 자리수 / 글자설정
    annot=True, fmt='.2f', annot_kws={'size':12, 'weight':'bold'},
    
    # 선 설정: 선 너비 / 선 색상
    linewidths=1, linecolor='white',
    
    # 추가 설정: 정사각형 / 마스크
    # mask: np.triu(corr), np.tril(corr)
    square=True, mask=np.triu(corr)
)
  • 스니펫으로 설정해서 불러올 수 있게 설정하면 끝
{
    "Seaborn Heatmap Template": {
        "prefix": "sns_heat",
        "body": [
            "sns.heatmap(",
            "    # 데이터 설정",
            "    data=${1:corr},",
            "",
            "    # 색상 설정: 컬러맵 / 컬러바 / 최소범위 / 최대범위 / 투명도 / 컬러바 중심점",
            "    # cmap: 'RdBu_r', 'coolwarm', 'YlOrRd', 'viridis', 'magma'",
            "    cmap='${2:RdBu_r}', cbar=${3:True}, vmin=${4:-1}, vmax=${5:1}, alpha=${6:0.8}, center=${7:0},",
            "",
            "    # 데이터값 표시: 소수점 자리수 / 글자설정",
            "    annot=${8:True}, fmt='${9:.2f}', annot_kws={'size':${10:12}, 'weight':'bold'},",
            "",
            "    # 선 설정: 선 너비 / 선 색상",
            "    linewidths=${11:1}, linecolor='${12:white}',",
            "",
            "    # 추가 설정: 정사각형 / 마스크",
            "    # mask: np.triu(corr), np.tril(corr)",
            "    square=${13:True}, mask=${14:np.triu(corr)}",
            ")"
        ],
        "description": "Create a Seaborn heatmap with common parameters"
    }
}

'Data Visualization > Seaborn' 카테고리의 다른 글

[Seaborn] 9. countplot  (0) 2024.11.15
[Seaborn] 8. pairplot  (0) 2024.11.15
[Seaborn] 7. jointplot  (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

댓글