<* Matplotlib 객체 지향 인터페이스 *>
◆ Matplotlib는 그래프를 다루는 두 가지의 인터페이스를 제공하는데
첫번째는 MATLAB 스타일로 pyplot 모듈을 사용하는 방식이고,
두번째는 객체 지향 인터페이스 이다.
---< 예제 : Graph_subplots01.py 그래프 plt.subplots() 사용하기 >-----------------------
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.show()
_________________________________________________________________________________________________
▶ matplotlib.pyplot 모듈은 subplots()라는 유용한 함수를 제공한다.
(matplotlib.pyplot.subplots)
▶ subplots() 함수를 호출하면 figure (fig)과 subplot (ax) 객체를 생성해서 튜플의 형태로 반환한다.
---< 예제 : Graph_subplots02.py 그래프 plt.subplots() 사용하기 >-----------------------
import matplotlib.pyplot as plt
# fig, ax = plt.subplots()
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
plt.show()
_________________________________________________________________________________________________
▶ fig, ax = plt.subplots()과 같이 사용하지 않고 이 예제와 같이 사용할 수도 있다.
▶ plt.figure()는 Figure 클래스의 인스턴스를 반환한다.
▶ Figure 클래스의 인스턴스 fig의 메서드 add_axes()는 fig에 axes를 하나 추가한다.
▶ add_axes([left, bottom, width, height])의 형태로 0에서 1 사이의 값을 입력한다.
▶ 예제들에서는 plt.subplots() 함수를 사용한다.
---< 예제 : Graph_nrows-ncols.py 행과 열 설정하기 (nrows, ncols) >------------------------
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
plt.show()
_____________________________________________________________________________________________________
▶ plt.subplots(nrows, ncols)의 형태로 행과 열의 개수를 지정할 수 있다.
▶ 만약 지정하지 않으면 기본적으로 행과 열의 개수는 모두 1입니다.
---< 예제 : Graph_XYshare.py X, Y축 공유하기 (sharex, sharey) >----------------------------
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True)
plt.show()
___________________________________________________________________________________________________________
▶ sharex=True, sharey=True로 설정함으로써 아래와 같이 중복된 축을 한번만 표시하도록 했다.
▶ sharex, sharey에 True, False 이 외에도 ‘all’, ‘none’, ‘row’, ‘col’ 등을 지정할 수 있다.
---< 예제 : Graph_subplots-NumPy.py 객체지향 그래프 그리기 >----------------------------
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5) # [1, 2, 3, 4]
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=True)
ax[0][0].plot(x, np.sqrt(x)) # left-top
ax[0][1].plot(x, x) # right-top
ax[1][0].plot(x, -x+5) # left-bottom
ax[1][1].plot(x, np.sqrt(-x+5)) # right-bottom
plt.show()
___________________________________________________________________________________________________________
▶ NumPy를 이용해서 x값들을 만들고, 네 개의 그래프 영역에 각각 다른 y값을 그래프로 나타냈다.
▶ plt.subplots()이 반환하는 ax는 Matplotlib의 Axes 클래스의 인스턴스 이다.
▶ 행과 열을 각각 2, 2로 지정했기 때문에 ax는 2×2의 형태를 갖는 NumPy 배열이 된다.
▶ 위치에 따라 각각 ax[0][0], ax[0][1], ax[1][0], ax[1][1]과 같이 접근해서 사용할 수 있다.
---< 예제 : Graph_subplots-Style.py 객체지향 스타일 설정하기 >----------------------------
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5) # [1, 2, 3, 4]
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=True)
ax[0][0].plot(x, np.sqrt(x), 'gray', linewidth=3)
ax[0][1].plot(x, x, 'g^-', markersize=10)
ax[1][0].plot(x, -x+5, 'ro--')
ax[1][1].plot(x, np.sqrt(-x+5), 'b.-.')
plt.show()
______________________________________________________________________________________________________
▶ plot()에 각각의 그래프의 스타일을 커스터마이즈하도록 설정할 수 있다.
---< 예제 : Graph_Title-.py 객체지향 제목과 범례 표시하기 >----------------------------
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 5) # [1, 2, 3, 4]
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=True)
ax[0][0].plot(x, np.sqrt(x), 'gray', linewidth=3, label='y=np.sqrt(x)')
ax[0][0].set_title('Graph 1')
ax[0][0].legend()
ax[0][1].plot(x, x, 'g^-', markersize=10, label='y=x')
ax[0][1].set_title('Graph 2')
ax[0][1].legend(loc='upper left')
ax[1][0].plot(x, -x+5, 'ro--', label='y=-x+5')
ax[1][0].set_title('Graph 3')
ax[1][0].legend(loc='lower left')
ax[1][1].plot(x, np.sqrt(-x+5), 'b.-.', label='y=np.sqrt(-x+5)')
ax[1][1].set_title('Graph 4')
ax[1][1].legend(loc='upper center')
plt.show()
_____________________________________________________________________________________
▶ set_title()과 legend()를 이용해서 각각의 그래프에 제목과 범례를 설정할 수 있다.
▶ set_title()은 입력한 문자열을 그래프의 제목으로 나타낸다.
▶ legend()는 plot()에서 label을 이용해서 지정한 문자열을 범례에 나타낸다.
▶ 그래프 영역에서 범례가 표시될 위치를 지정할 수 있는데,
지정하지 않으면 최적의 위치에 범례를 표시한다.
--- 범례가 표시될 위치를 설정하기 위한 옵션 ------
'best'
'upper right'
'upper left'
'lower left'
'lower right'
'right'
'center left'
'center right'
'lower center'
'upper center'
'center'