건프의 소소한 개발이야기

[Python-Jupyter] Matplotlib 그래프 여러개 그리기 본문

개발 이야기/Machine Learning 이야기

[Python-Jupyter] Matplotlib 그래프 여러개 그리기

건강한프로그래머 2017. 2. 12. 20:04

안녕하세요, 건프입니다.


python 의 그래프를 그리는 유용한 툴인 Matplotlib 으로

데이터를 다룰때 시각화를 하다보니


그래프 한개를 쓰는법은 잘 알겠는데, (http://matplotlib.org/users/pyplot_tutorial.html)

그래프를 한번에 여러개를 그리는 방법에 대해서는 잘 모르겠더라구요.


그래서 한번 정리해서 메모해봅니다.


작업한 환경은 Python 3.5+, Jupyter notebook 위에서 작업했습니다.



Matplotlib-Multiple Subplot
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import warnings
In [5]:
def example_plot(ax):
    ax.plot([1,2])
    ax.set_xlabel('x-label')
    ax.set_ylabel('y-label')
    ax.set_title('Title')
In [4]:
fig, ax = plt.subplots()
example_plot(ax)
plt.tight_layout()
In [8]:
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
In [14]:
fig, axes = plt.subplots(nrows=3, ncols=3)
print(type(axes))
print(axes.shape)
for row in axes:
    for each_ax in row:
        example_plot(each_ax)
plt.tight_layout()
<class 'numpy.ndarray'>
(3, 3)
In [15]:
fig = plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
plt.tight_layout()

순서를 바꿔도 똑같다?

In [17]:
fig = plt.figure()
ax1 = plt.subplot(221)
ax3 = plt.subplot(122)
ax2 = plt.subplot(223)
example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
plt.tight_layout()
In [18]:
fig = plt.figure()
ax1 = plt.subplot2grid((3,3), (0,0))
ax2 = plt.subplot2grid((3,3), (0,1), colspan=2)
ax3 = plt.subplot2grid((3,3), (1,0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3,3), (1,2), rowspan=2)

example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
plt.tight_layout()
In [19]:
import matplotlib.gridspec as gridspec
In [20]:
fig = plt.figure()

gs1 = gridspec.GridSpec(3,1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
ax3 = fig.add_subplot(gs1[2])

example_plot(ax1)
example_plot(ax2)
example_plot(ax3)

gs1.tight_layout(fig, rect=[None, None, 0.45, None])
In [31]:
fig = plt.figure()

gs1 = gridspec.GridSpec(3,1)
ax1 = fig.add_subplot(gs1[0])
ax2 = fig.add_subplot(gs1[1])
ax3 = fig.add_subplot(gs1[2])

example_plot(ax1)
example_plot(ax2)
example_plot(ax3)

gs1.tight_layout(fig, rect=[None, None, 0.45, None])

# 앞에꺼랑 이어서 한다면?
gs2 = gridspec.GridSpec(1, 2)
ax4 = fig.add_subplot(gs2[0])
ax5 = fig.add_subplot(gs2[1])
example_plot(ax4)
example_plot(ax5)
gs2.tight_layout(fig, rect=[0.45, None, None, None])

top = min(gs1.top, gs2.top)
bottom = max(gs1.bottom, gs2.bottom)

gs1.update(top=top, bottom=bottom)
gs2.update(top=top, bottom=bottom)
/Users/myZZUNG/myworkspace/kaggle-study/jupyter/lib/python3.5/site-packages/matplotlib/gridspec.py:302: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.
  warnings.warn("This figure includes Axes that are not "
In [ ]:
 


Comments