visualization
subplot & set
siwoli
2022. 4. 6. 09:30
subplots()
: figure객체와 axes객체를 나눠 받는 method로 여기서 axes객체란, 하나의 그래프 객체라고 생각하면 된다.
figue객체 안에 axes객체가 포함되고 axes객체는 여러개 생성 가능하므로 한번에 여러 그래프를 나타낼수 있다.
- plt.subplots(행, 열): axes객체가 numpy배열 타입으로 생성
--> 인덱스로 각 axes객체에 접근 가능 - figue.set_size_inches(가로, 세로): figure의 크기 지정(일종의 그림틀 크기 지정이라고 생각하면 된다.)
- figue.add_subplot(행, 열, 칸 번호): 하나의 axes객체를 figure객체에 집어넣는 것
.set(title='', xlabel='', ylabel='')
: 그래프 제목, x축 및 y축 제목 설정
subplots()함수는 figure객체와 axes객체를 한번에 선언한다.
그리고 (행 개수, 열 개수)를 지정하면 axes객체가 numpy배열 타입으로 생성된다.
figue, axes = plt.subplots(nrows=1, ncols=2)
print(axes, "\n", type(axes))
>[<matplotlib.axes._subplots.AxesSubplot object at 0x7f2c0d1406d0>
<matplotlib.axes._subplots.AxesSubplot object at 0x7f2c0d0e1550>]
<class 'numpy.ndarray'>
이번엔 figure객체를 생성한후 axes객체를 넣어보자.
figure()로 figure객체를 생성하고
set_size_inches()로 figure객체 크기를 지정한다.
그리고 add_subplot()으로 axes객체를 figure안에 넣어준다.
이때 axes객체의 위치를 행렬 인덱스 기반으로 지정해줄 수 있다.
마지막으로 plot()으로 각 axes객체에 그래프를 지정하면 텅빈 좌표평면에서 다음과 같이 그래프가 나타난다.
import matplotlib.pyplot as plt
import numpy as np
#cos함수
x_1 = range(100)
y_1 = [np.cos(value) for value in x_1]
#sin함수
x_2 = range(100)
y_2 = [np.sin(value) for value in x_2]
fig = plt.figure()
fig.set_size_inches(10, 10)
# figue의 행은 1개, 열은 2개로 하여 그래프 생성
ax_1 = fig.add_subplot(1,2,1) # 1행 2열 중 1열
ax_2 = fig.add_subplot(1,2,2) # 1행 2열 중 2열
ax_1.plot(x_1, y_1, c="b") # color="blue"
ax_2.plot(x_2, y_2, c="g") # color="green"
plt.show()
>