PYTHON/Python

Python seaborn 서브플롯 생성 기초 정리

진리뷰 2024. 4. 10. 09:00
반응형

 

 

 

Python-seaborn-서브플롯-생성-기초-정리-썸네일
Python seaborn 서브플롯

 

 

 

 이 글은 Python seaborn 서브플롯 개념과 생성 예시, 옵션 설정 메서드 기초 정리를 담고 있습니다.

 

 

 

Python seaborn 서브플롯

 

seaborn은 sns로 쓰인다. 따라서 sns라고 지칭하겠다.

sns은 matplotlib의 상위 호환 같은 라이브러리인데, 이 때문에 matplotlib 서브플롯을 사용한다.

plt.subplots(행 개수, 열 개수)

 

만약 서브플롯 개념과 생성법이 궁금하다면, 지난 글 참고를 추천드린다.

* 관련 글 추천 Python matplotlib 서브플롯 fig, ax(s) 개념과 사용법 기초 정리

 

 

 

Python seaborn 서브플롯 생성 예시

 

먼저 서브플롯 생성을 위해 fig, axs를 생성한다.

sns 서브플롯 생성 시, 인덱싱 법칙에 따라 0부터 입력한다.

import matplotlib.pyplot as plt
import seaborn as sns

# 서브플롯 생성
fig, axs = plt.subplots(2, 1, figsize(20,10))

# 서브플롯에 그래프 그리기
sns.histplot(df['price'], ax=axs[0])
sns.kdeplot(df['price'], ax=axs[1])

# 그래프별 타이틀 설정
axs[0].set_title('Histogram of price')
axs[1].set_title('KDE of price')

# 그래프 겹침 방지, 간격 자동 설정
plt.tight_layout();

 

 

2행 1열로 두 그래프(histplot, kdeplot)를 그린 결과이다.

 

python-seaborn-subplots-예시1
seaborn subplots 예시1

 

 

만약 서브플롯 별로 옵션을 설정하고 싶다면, 위에서 보인 타이틀 설정 코드처럼 서브플롯 위치(인덱스)를 명확히 입력해야 한다.

 

import matplotlib.pyplot as plt
import seaborn as sns

fig, axs = plt.subplots(2, 1, figsize=(20,10))
sns.histplot(df['price'], ax=axs[0])
sns.kdeplot(df['price'], ax=axs[1])

# 서브플롯 별 옵션 설정
axs[0].set_title('<Histogram of price>', color='tab:red')
axs[0].set_xlabel('Price', fontsize=12, color='tab:red')

axs[1].set_title('<KDE of price>', color='tab:blue')
axs[1].set_xlabel('Price', fontsize=12, color='tab:blue')

plt.tight_layout();

 

 

간단하게 그래프 색상, 타이틀과 x축 레이블의 내용 및 색상을 설정한 결과이다.

 

seaborn-subplots-예시2
seaborn suplots 예시2

 

 

 

서브플롯 옵션 설정 메서드

 

  • set_title()

서브플롯의 제목 설정.

위 그래프 예시처럼 set_title('<KDE of price>')는 서브플롯의 제목으로 해당 텍스트가 표시됨.

  • set_xlabel()

x축 레이블 설정.

위 그래프 예시처럼 set_xlabel('Price')은 x축 label에 Price가 표시됨.

  • set_ylabel()

x축 레이블 설정, set_xlabel()처럼 텍스트 입력.

  • set_xticks()

x축 눈금값 범위를 설정.

예를 들어 set_xticks([0, 25, 50])은 값의 범위가 0~50이며, 중앙값은 25로 눈금 설정 됨.

  • set_yticsk()

y축 눈금값 범위를 설정.

set_xticks()처럼 값의 범위 입력

  • set_xticklabels()

x축 눈금값의 이름 설정.

예를 들어,  set_xticks([0, 25, 50])과 set_xticklabels(['Min', 'Mean', 'Max'])으로 설정한다면 다음과 같다.

x축 눈금값 0은 0이 아닌 Min으로 표시, 눈금값 25는 25가 아닌 Mean으로 표시, 눈금값 50은 50이 아닌 Max로 표시됨.

  • set_yticklabels()

y축 눈금값의 이름 설정. xticklabels()처럼 설정하려는 이름 입력.

  • get_xticklabels().

x축 기본 눈금값을 가져 옴.

  • get_yticklabels()

y축 기본 눈금값을 가져 옴.

  • tick_params()

tick은 눈금으로, 눈금의 스타일을 설정.

* tick_params 관련 추천 글

 

13. Matplotlib 눈금 표시하기

![](https://wikidocs.net/images/page/92089/set_ticks_00.png) **틱 (Tick)**은 그래프의 **축에 간격을 구분하기 위해…

wikidocs.net

 

반응형
top