오답노트

[matplotlib] 여러 그래프 나누어 그리기 본문

Python/Matplotlib

[matplotlib] 여러 그래프 나누어 그리기

권멋져 2022. 8. 10. 20:57

sublpot

plt.subplot(row, col, index)
  • row : 세로로 생성할 차트 개수
  • col : 가로로 생성할 차트 개수
  • index : 차트의 위치 (1부터 시작)

subplot은 여러 차트를 한번에 출력할 수 있다.

plot 함수를 사용하기 전에 먼저 호출하여 사용해야한다.

다음 subplot을 만나기전까지 plot에 plt 함수가 적용된다.

lst1 = list(range(1,6))
lst2 = list(range(2,7))
lst3 = list(range(11,16))
lst4 = list(range(12,17))

plt.subplot(2,2,1)
plt.plot(lst1)
plt.title("lst1")

plt.subplot(2,2,2)
plt.plot(lst2)
plt.title("lst2")

plt.subplot(2,2,3)
plt.plot(lst3)
plt.title("lst3")

plt.subplot(2,2,4)
plt.plot(lst4)
plt.title("lst4")

plt.show()

 

1.1 4개의 차트를 한 번에 출력

tight_layout

사진1.1을 보면 타이틀이 x축과 겹치는 현상이 나타난다. 

이 때 tight_layout 함수를 사용하면 보기 좋게 적절히 차트들이 이동하거나 크기가 조절된다.

 

lst1 = list(range(1,6))
lst2 = list(range(2,7))
lst3 = list(range(11,16))
lst4 = list(range(12,17))

plt.subplot(2,2,1)
plt.plot(lst1)
plt.title("lst1")

plt.subplot(2,2,2)
plt.plot(lst2)
plt.title("lst2")

plt.subplot(2,2,3)
plt.plot(lst3)
plt.title("lst3")

plt.subplot(2,2,4)
plt.plot(lst4)
plt.title("lst4")

######
plt.tight_layout()
######

plt.show()

2.1 적절하게 조절된 4개의 차트