728x90
figure canvas를 분할하는 subplot
- 하나의 이미지에 다단으로 이미지를 삽입하고자 할 때 subplot으로 canvas를 분할하고 위치를 지정할 수 있다.
plt.subplot(행, 열, 인덱스)
행과 열에서 형태를 지정하고 인덱스로 그래프를 넣을 위치를 지정하게 된다. canvas를 행과 열에 맞게 분할하고 인덱스로 figure를 삽입할 위치를 지정한다.- 아래는
plt.subplot(3,2,idx)
로 canvas를 분할한 예시이다.

고정된 분할
- 예를 들어 canvas를 4개의 행으로 분리해 4개의 figure를 그리고 싶을 때는
plt.subplot(4,1,인덱스)
를 고정으로 사용하면 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
import numpy as np | |
x = np.linspace0,np.pi | |
y_1 = np.sinx | |
y_2 = np.sinx + np.random.normal0,0.1,50 | |
y_3 = np.sinx + np.random.uniforma−0.1,0.1,50 | |
y_4 = np.sinx + np.random.normal0,0.01,50 | |
plt.figurefigsize=(15,10) | |
plt.subplot2,2,1 | |
plt.title′subtitleone′ | |
plt.plotx,y1 | |
plt.subplot2,2,2 | |
plt.plotx,y2 | |
plt.title′subtitletwo′ | |
plt.subplot2,2,3 | |
plt.plotx,y3 | |
plt.title′subtitlethree′ | |
plt.subplot2,2,4 | |
plt.plotx,y4 | |
plt.title′subtitlefour′ | |
plt.suptitle′SUPTITLE′,fontsize=20 |

유연한 분할
- 만약 1행에는 1개의 figure를 그리고, 2행에는 3개의 figure를 그린다면 다음과 같이 하면 된다.
- 1행에 1개의 figure를 그리기 위해서는
plt.subplot(2,1,2)
로 2개의 행으로 나누어 1번째 인덱스를 지정한다 - 2행에 삽입할 figure들은 3개의 열로 나누어야하기 때문에
plt.subplot(2,3,idx)
로 위치를 지정해주면 된다.- 그런데 여기에서 idx는 전체 canvas를 2행 3열로 나누었다고 생각하고 지정해주어야 한다.
- 2행의 idx의 시작은 4부터 시작하기 때문에
plt.subplot(2,3,4)
위치에 figure를 그려주면 원하는 결과를 얻을 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
plt.figurefigsize=(15,10) | |
plt.subplot2,1,1 | |
plt.title′subtitleone′ | |
plt.plotx,y1 | |
plt.subplot2,3,4 | |
plt.plotx,y2 | |
plt.title′subtitletwo′ | |
plt.subplot2,3,5 | |
plt.plotx,y3 | |
plt.title′subtitlethree′ | |
plt.subplot2,3,6 | |
plt.plotx,y4 | |
plt.title′subtitlefour′ | |
plt.suptitle′SUPTITLE′,fontsize=20 |

마무리
- subplot는 시계열 데이터의 같은 시점을 비교하거나, 다수의 figure를 비교해야하는 경우에 빈번하게 사용되는 방법이다.
- 알고리즘 학습 결과를 시각화 할 때, 다른 크기의 figure를 삽입할 필요가 있었는데 이 방법으로 구현했었다.
'프로그래밍 언어 > python' 카테고리의 다른 글
matplotlib 테마 설정하기 0 | 2022.07.26 |
---|---|
lambda 함수 0 | 2022.07.26 |
numpy array를 사용할 때 for문을 피해야하는 이유 0 | 2022.07.26 |
python 함수를 아름답게 사용하기 0 | 2022.07.26 |
_var, var_, _var_, __var__과 같이 선언된 변수의 의미를 설명 0 | 2022.07.26 |