seaborn layout 동적으로 만드는 방법 소개

2020. 4. 19. 18:04분석 Python/Visualization

728x90

python에서는 시각화를 할 때 이쁘게 그려주는 seaborn을 많이들 사용한다.
seaborn을 사용할 때 subplot을 어떻게 주면 좋을지에 대해서 발견한 코드를 공유한다.

import seaborn as sns
import pandas as pd
titanic = pd.read_csv("./../DATA/train.csv")
titanic.head()

아래 코드에서는 컬럼을 몇 열로 할지만 정해주면 동적으로 행을 채워준다.

categorical_vars = ['Survived','Pclass','Sex','SibSp','Parch','Cabin','Embarked']
num_plots = len(categorical_vars)
total_cols = 3
total_rows = num_plots//total_cols + 1
fig, axs = plt.subplots(nrows=total_rows, ncols=total_cols,
                        figsize=(7*total_cols, 7*total_rows), constrained_layout=True)
for i, var in enumerate(categorical_vars):
    row = i//total_cols
    pos = i % total_cols
    plot = sns.countplot(x=var, data=titanic,
                         hue = "Survived",
                         ax=axs[row][pos])

하지만 기존 코드에서 아쉬운 부분은 쓸모없는 부분도 layout이 표현된다.
그래서 이 부분을 동적으로 없앨 수 있는 코드를 만들어봤다.

num_plots = len(categorical_vars)
total_cols = 3
total_rows = num_plots//total_cols + 1
fig, axs = plt.subplots(nrows=total_rows, ncols=total_cols,
                        figsize=(7*total_cols, 7*total_rows), constrained_layout=True)
for i, var in enumerate(categorical_vars):
    row = i//total_cols
    pos = i % total_cols
    plot = sns.countplot(x=var, data=titanic,
                         hue = "Survived",
                         ax=axs[row][pos])
if total_rows * total_cols > len(categorical_vars) :
    remainder_n = total_rows * total_cols - len(categorical_vars)
    for i in range(remainder_n) :
        axs[row][-(i+1)].axis("off")

 

그러면 위의 코드랑은 달리게 표현되지 않는 부분은 없어지는 것을 확인할 수 있었다!
이번엔 layout의 총 열을 6개로 지정해봤다.

num_plots = len(categorical_vars)
total_cols = 6
total_rows = num_plots//total_cols + 1
fig, axs = plt.subplots(nrows=total_rows, ncols=total_cols,
                        figsize=(7*total_cols, 7*total_rows), constrained_layout=True)
for i, var in enumerate(categorical_vars):
    row = i//total_cols
    pos = i % total_cols
    plot = sns.countplot(x=var, data=titanic,
                         hue = "Survived",
                         ax=axs[row][pos])
if total_rows * total_cols > len(categorical_vars) :
    remainder_n = total_rows * total_cols - len(categorical_vars)
    for i in range(remainder_n) :
        axs[row][-(i+1)].axis("off")

!!

 

 

 

https://towardsdatascience.com/dynamic-subplot-layout-in-seaborn-e777500c7386

 

Dynamic subplot layout in Seaborn

Seaborn is one of the most used visualization libraries and I enjoy working with it. In my latest projects, I wanted to visualize multiple…

towardsdatascience.com

 

728x90