노트와 노트

[시각화] matplotlib과 seaborn 라이브러리를 활용해 여러 개의 barplot 그리기 본문

Data Analysis

[시각화] matplotlib과 seaborn 라이브러리를 활용해 여러 개의 barplot 그리기

gellygelly 2022. 5. 3. 19:52

데이터를 그래프로 시각화하다보면 하나의 화면에 여러 개의 그래프를 띄우고 싶을 때가 있다. 

 

아래 화면은 matplotlib와 seaborn의 barplot 함수를 이용하여 2rows * 5cols 형태의 10개 그래프를 띄운 예시이다. 

 

Seaborn.barplot documentation

seaborn.barplot의 파라미터 및 그래프 하나를 그리는 간단한 예제는 아래 seaborn documentation에서 확인 가능하다. 

seaborn.barplot — seaborn 0.11.2 documentation (pydata.org)

 

seaborn.barplot — seaborn 0.11.2 documentation

Vectors of data represented as lists, numpy arrays, or pandas Series objects passed directly to the x, y, and/or hue parameters.

seaborn.pydata.org

 

구현

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

def show_graph():
    fig, ax = plt.subplots(figsize=(25, 16), nrows=2, ncols=5)  # 2행 5열의 그래프 생성
    plt.subplots_adjust(left=0.06, bottom=0.1, right=0.95, top=0.945, wspace=0.6, hspace=0.35) # 간격 조정
    season_list = ['S/S', 'F/W'] # shirt
    year_list = ['2018', '2019', '2020', '2021', '2022'] # shirt

    for i, season in enumerate(season_list):
        for j, year in enumerate(year_list):
        	# comp_counter 함수: DB에서 해당하는 조건의 데이터를 추출하여 리턴하는 함수
            # data 
            comp_list, count_list, sex_, year_, season_ = \
                comp_counter(db, 'pattern', item_type='shirt', sex='여', season=season, year=year)
            print(comp_list, count_list, sex_, year_, season_)
            
            # df 형태로 변환
            df = pd.DataFrame(data=count_list, index=comp_list, columns=['count'])
            print(df)
            
            # 개별 그래프에 인덱스 형태로 접근하여 제목 및 그래프 값 표시
            ax[i][j].set_title("{0} {1}".format(season, year))
            for k in range(0, len(count_list)):
                ax[i][j].annotate(count_list[k], (count_list[k]*1, k), )

            sns.barplot(x='count', y=df.index, data=df, ax=ax[i][j], palette="husl")

    plt.show()

 

각 그림은 ax[i][j] 처럼 인덱스를 지정하여 개별적으로 접근 가능하다. 

 

위 코드의 comp_counter()는 데이터를 불러오는 부분이므로, 실제 사용할 때에는 각자의 데이터셋을 불러와서 df 형태로 변환 후 sns.barplot() 함수의 데이터로 넣어주면 된다. 

 

matplotlib.pyploy의 annotate 함수의 인자는 아래 documentation에서 확인 가능하다.

https://matplotlib.org/3.5.0/api/_as_gen/matplotlib.pyplot.annotate.html?highlight=annotate#matplotlib.pyplot.annotate 

 

matplotlib.pyplot.annotate — Matplotlib 3.5.0 documentation

An Artist: xy is interpreted as a fraction of the artist's Bbox. E.g. (0, 0) would be the lower left corner of the bounding box and (0.5, 1) would be the center top of the bounding box.

matplotlib.org