본문 바로가기

Programming/Data mining

4. Matplotlib Architecture _ python

Coursera.org 에서 Michigan University의 Applied Data Science with Python의 강의를 토대로 정리한 내용입니다.

 이번 포스팅부터는 본격적으로 Matplotlib 라이브러리에 대해서 다루어보려고 한다.
먼저 Matplotlib의 기본적인 구조부터 살펴보도록 하자.

1. Backend Layer
먼저 backend layer는 우리가 스크린이나 파일에 plot을 그릴 수 있도록 해준다.

2. Artist Layer
Figure나 Subplot, Axes 등을 포함하는 컨테이너이다. 그려지는 거의 모든 것들은 이 artist layer와 매칭된다고 보면 된다.

3. Scripting Layer
사실 plot하는 과정은 위의 backend와 artist layer만 잘 이용한다면 모두 가능하다. 하지만 이는 실제로 상당히 복잡하고 귀찮은 일이 될 수 있다. 이에 matplotlib에서 제공하는 것이 바로 scripting layer이다. 여기에서 우리는 artist layer와 backend layer를 간단하게 조작할 수 있는 마법같은 명령들을 내릴 수 있게 된다.

코드를 통해 살펴보자. 1줄의 코드가 5줄이 넘어가는 불편함을 알 수 있다.

#아래는 (3,2)의 좌표에 red 점을 scripting layer를 이용하여 plot하였다.

import matplotlib.pyplot as plt
plt.plot(3, 2, '.r')

#아래에는 같은 작업을 backend layer와 artist layer를 이용하여 plot하였다.
# First let's set the backend without using mpl.use() from the scripting layer
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure

# create a new figure
fig = Figure()

# associate fig with the backend
canvas = FigureCanvasAgg(fig)

# add a subplot to the fig
ax = fig.add_subplot(111)

# plot the point (3,2)
ax.plot(3, 2, '.')

# save the figure to test.png
# you can see this figure in your Jupyter workspace afterwards by going to
# https://hub.coursera-notebooks.org/
canvas.print_png('test.png')

%%html
<img src='test.png' />

 

추가적으로 gca()나 gcf() method를 이용하여 우리는 axes 나 figure에 접근하고 이를 조작할 수 있다.

ax = plt.gca()
# Set axis properties [xmin, xmax, ymin, ymax]
ax.axis([0,6,0,10])

#위의 코드를 통해 plt의 axes에 접근하여 axis의 범위를 설정해줄 수도 있다