python 메모

[matplotlib] subplot 그리기

Fine애플 2021. 5. 19. 14:33

matplotlib.pyplot을 활용하여 여러개의 subplot을 사용하는 방법은 간단하다. 다음과 같은 데이터가 있고 각 label별 class의 분포를 하나의 figure에서 표현하고자 한다.

 

 

plt.subplot은 각 subplot을 그릴 때 호출하면 되며 (nrow, ncolumns, index) 값을 넣어주면 된다.

  • nrows: 총 row 개수
  • ncolumns: 총 column 개수
  • index: 해당 subplot이 몇 번째 subplot인지 
plt.figure(figsize=(16,12))
for plot_idx, col in enumerate(nd.columns):
    d = nd[col]
    c_val = d.value_counts().to_dict()
    n_dict = dict()
    for i, (c, v) in enumerate(c_val.items()):
        n_dict[str(i)] = v
    
    plt.subplot(2,2,plot_idx+1)  ## index는 1부터
    plt.bar(n_dict.keys(), n_dict.values(), color='C%d'%plot_idx)
    plt.grid(True, axis='y', alpha=0.7, linestyle='--')
    plt.title(col, fontsize=20)

 

결과는 다음과 같이 나온다.

subplot 결과

 

 

 

728x90