[파이썬] seaborn 플롯 간의 간격과 여백 조절하기

여백 조절하기

seaborn의 플롯 함수는 기본적으로 matplotlib.pyplot 라이브러리를 기반으로 합니다. 따라서 seaborn 플롯의 여백을 조절하는 방법은 matplotlib.pyplot.subplots 함수를 사용하는 것과 동일합니다.

여백을 조절하기 위해서는 다음의 두 가지 방법을 사용할 수 있습니다:

1. fig.subplots_adjust

import seaborn as sns
import matplotlib.pyplot as plt

# 데이터 로드
tips = sns.load_dataset("tips")

# 플롯 생성
fig, ax = plt.subplots()

# 여백 조절
fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)

# seaborn 플롯 생성
sns.scatterplot(data=tips, x="total_bill", y="tip", ax=ax)

# 플롯 보여주기
plt.show()

위의 예제에서 fig.subplots_adjust 함수 내의 left, bottom, right, top 매개변수를 사용하여 각각 왼쪽, 아래, 오른쪽, 위의 여백을 조절할 수 있습니다.

2. plt.subplotssubplot_kw 매개변수

import seaborn as sns
import matplotlib.pyplot as plt

# 데이터 로드
tips = sns.load_dataset("tips")

# 여백 조절을 위한 subplot_kw 매개변수 설정
fig, ax = plt.subplots(subplot_kw={"left": 0.1, "bottom": 0.1, "right": 0.9, "top": 0.9})

# seaborn 플롯 생성
sns.scatterplot(data=tips, x="total_bill", y="tip", ax=ax)

# 플롯 보여주기
plt.show()

위의 예제에서는 plt.subplots 함수의 subplot_kw 매개변수를 사용하여 여백을 조절합니다. 이 방법은 fig.subplots_adjust 함수를 사용하는 것보다 좀 더 편리한 방법입니다.

간격 조절하기

seaborn에서 플롯 간의 간격을 조절하기 위해서는 matplotlib.pyplot.subplots 함수의 hspacewspace 매개변수를 사용할 수 있습니다.

import seaborn as sns
import matplotlib.pyplot as plt

# 데이터 로드
tips = sns.load_dataset("tips")

# 플롯 생성
fig, axs = plt.subplots(2, 2, figsize=(10, 10), sharex=True, sharey=True)

# 간격 조절
fig.subplots_adjust(hspace=0.5, wspace=0.3)

# seaborn 플롯 생성
sns.scatterplot(data=tips, x="total_bill", y="tip", ax=axs[0, 0])
sns.histplot(data=tips, x="total_bill", ax=axs[0, 1])
sns.boxplot(data=tips, x="day", y="total_bill", ax=axs[1, 0])
sns.countplot(data=tips, x="sex", ax=axs[1, 1])

# 플롯 보여주기
plt.show()

위의 예제에서 fig.subplots_adjust 함수의 hspacewspace 매개변수를 사용하여 플롯들 사이의 세로 간격과 가로 간격을 조절할 수 있습니다.

이제 여러분은 seaborn 플롯의 간격과 여백을 조절하는 방법을 익혔습니다. 이러한 조절 기능을 사용하여 결과물을 원하는대로 꾸밀 수 있습니다. 향후 seaborn을 사용할 때 자신만의 멋진 시각화를 만드는 데 도움이 될 것입니다.