[참조]
- 공학자를 위한 Python, 조정래, 2022: 4. Matplotlib
https://wikidocs.net/14570 - Dookie Kim, Python: From Beginning to Application, 2022 [PDF]
Matplotlib은 그래프를 그리는 패키지이다.
(3) 사용법
1) matplotlib 구동 방식
a) API 객체 방식: matplotlib의 객체지향라이브러리 활용
b) plt 함수 방식: 객체지향 API로 구현한 matplotlib.pyplot 모듈의 함수
- API 객체는 다음 3가지 객체로 구성되어 있다
a) FigureCanvas: 그림 캔퍼스
b) Renderer: FigureCanvas에 그리는 도구
c) Artist: Renderer가 FigureCanvas에 그리는 방법
- Artist 객체의 2가지 유형은 다음과 같다.
a) Primitives: Line2D, Rectangle, Text, AxesImage, Patch 등으로 캔버스에 그려지는 객체
b) Containers: Axis, Axes, Figure 등으로 primitives가 위치할 대상
-
Ex) API 객체 방식
import matplotlib.pyplot as plt import numpy as np X = np.linspace(0,1,40) Y1 = np.cos(4*np.pi*X) Y2 = np.cos(4*np.pi*X)*np.exp(-2*X) fig = plt.figure() # figure 객체 생성 ax = fig.subplots() # axes 생성 ax.plot(X,Y1,'r-*',lw=1) # axes에 plot() 함수 ax.plot(X,Y2,'b--',lw=1) -
Ex) plt.plot 함수 방식
import matplotlib.pyplot as plt import numpy as np X = np.linspace(0,1,40) Y1 = np.cos(4*np.pi*X) Y2 = np.cos(4*np.pi*X)*np.exp(-2*X) plt.plot(X,Y1,'r-*',lw=1) # plt의 plot() 함수 plt.plot(X,Y2,'b--',lw=1) -
Ex) API 객체 방식 + plt.subplots 함수 방식
import matplotlib.pyplot as plt import numpy as np X = np.linspace(0,1,40) Y1 = np.cos(4*np.pi*X) Y2 = np.cos(4*np.pi*X)*np.exp(-2*X) fig,ax = plt.subplots() # plt.subplots() 함수는 figure 객체 생성, ax=figure.subplots()를 호출 ax.plot(X,Y1,'r-*',lw=1) ax.plot(X,Y2,'b--',lw=1)
2) axes vs axis
- Axes
plot으로 나타낸 하나의 그래프(또는 차트). 각각의 Axes는 개별적인 제목 및 x, y label을 가질 수 있다.
- Axis
x축, y축의 범위

3) subplot
-
Ex) API 객체 방식 import matplotlib.pyplot as plt import numpy as np X = np.linspace(0,1,40) Y1 = np.cos(4*np.pi*X) Y2 = np.cos(4*np.pi*X)*np.exp(-2*X) fig = plt.figure() ax = fig.add_subplot(2,1,1) ax.plot(X,Y1,'r-*',lw=1) ax.grid(True) ax.set_ylabel(r'$sin(4 \pi X)