fig.add_subplot 의 sharex 또는 sharey 인자로 공유할 ax를 선택할 수도 있고 plt.subplots 으로 초기에 fig를 생성할 때 이 값을 True 로 설정하면서 공유할 수도 있다.
2-3. squeeze와 flatten
squeeze
subplots()로 생성하면 기본적으로 다음과 같이 서브플롯 ax 배열이 생성됩니다.
1 x 1 : 객체 1개 (ax)
1 x N 또는 N x 1 : 길이 N 배열 (axes[i])
N x M : N by M 배열 (axes[i][j])
numpy ndarray에서 각각 차원이 0, 1, 2로 나타납니다. 이렇게 되면 경우에 따라 반복문을 사용할 수 있거나, 없거나로 구분됩니다.
squeeze를 사용하면 항상 2차원으로 배열을 받을 수 있고, 가변 크기에 대해 반복문을 사용하기에 유용합니다.
n, m = 1, 3
fig, axes = plt.subplots(n, m, squeeze=False, figsize=(m*2, n*2))
idx = 0
for i in range(n):
for j in range(m):
axes[i][j].set_title(idx)
axes[i][j].set_xticks([])
axes[i][j].set_yticks([])
idx+=1
plt.show()
plt.subplots()나 plt.gca()로 받는 ax 리스트는 numpy ndarray로 전달됩니다.
그렇기에 1중 반복문을 쓰고 싶다면 flatten() 메서드를 사용할 수 있습니다.
n, m = 2, 3
fig, axes = plt.subplots(n, m, figsize=(m*2, n*2))
for i, ax in enumerate(axes.flatten()):
ax.set_title(i)
ax.set_xticks([])
ax.set_yticks([])
plt.show()
fig = plt.figure(figsize=(8, 5))
gs = fig.add_gridspec(3, 3) # make 3 by 3 grid (row, col)
ax = [None for _ in range(5)]
ax[0] = fig.add_subplot(gs[0, :])
ax[0].set_title('gs[0, :]')
ax[1] = fig.add_subplot(gs[1, :-1])
ax[1].set_title('gs[1, :-1]')
ax[2] = fig.add_subplot(gs[1:, -1])
ax[2].set_title('gs[1:, -1]')
ax[3] = fig.add_subplot(gs[-1, 0])
ax[3].set_title('gs[-1, 0]')
ax[4] = fig.add_subplot(gs[-1, -2])
ax[4].set_title('gs[-1, -2]')
for ix in range(5):
ax[ix].set_xticks([])
ax[ix].set_yticks([])
plt.tight_layout()
plt.show()
3-2. subplot2grid
N x M 그리드에서 시작점에서 delta x, delta y로 표현할 수 있습니다.
개인적으로는 add_gridspec을 더 선호합니다.
fig = plt.figure(figsize=(8, 5)) # initialize figure
ax = [None for _ in range(6)] # list to save many ax for setting parameter in each
ax[0] = plt.subplot2grid((3,4), (0,0), colspan=4)
ax[1] = plt.subplot2grid((3,4), (1,0), colspan=1)
ax[2] = plt.subplot2grid((3,4), (1,1), colspan=1)
ax[3] = plt.subplot2grid((3,4), (1,2), colspan=1)
ax[4] = plt.subplot2grid((3,4), (1,3), colspan=1,rowspan=2)
ax[5] = plt.subplot2grid((3,4), (2,0), colspan=3)
for ix in range(6):
ax[ix].set_title('ax[{}]'.format(ix)) # make ax title for distinguish:)
ax[ix].set_xticks([]) # to remove x ticks
ax[ix].set_yticks([]) # to remove y ticks
fig.tight_layout()
plt.show()
3-3. add_axes
특정 플롯을 임의의 위치에 만드는 메서드입니다.
위치를 조정하여 그래프를 그리는 게 쉽지는 않기 때문에 추천하지 않습니다.
fig = plt.figure(figsize=(8, 5))
ax = [None for _ in range(3)]
ax[0] = fig.add_axes([0.1,0.1,0.8,0.4]) # x, y, dx, dy
ax[1] = fig.add_axes([0.15,0.6,0.25,0.6])
ax[2] = fig.add_axes([0.5,0.6,0.4,0.3])
for ix in range(3):
ax[ix].set_title('ax[{}]'.format(ix))
ax[ix].set_xticks([])
ax[ix].set_yticks([])
plt.show()