matplotlib

matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

matplotlib은 다음과 같이 설치할 수 있다.

$sudo apt-get install python-matplotlib

1. 직선 그래프 그리기
다음은 (0, 1), (1, 2), (2, 3), (3, 4)를 2차원 좌표공간 위에 그리는 예제이다[2].

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

null

line에는 속성이 있으며, 이를 지정해 그래프의 형태를 조절할 수 있다.

속성 지정에는 세 가지 방법이 있다.
1) 인자값으로 전달

plt.plot(x, y, linewidth=2.0)

2) Line2D instance의 setter method 사용

line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialising

3) setp() method 사용

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

주어진 객체에 설정 가능한 속성은 setp() method로 확인할 수 있다.

In [69]: lines = plt.plot([1,2,3])
In [70]: plt.setp(lines)
  alpha: float
  animated: [True | False]
  antialiased or aa: [True | False]
  ...snip

2. Subplot 그리기
pyplot은 subplot을 지원하며, subplot을 사용해 한 파일 안에 여러 개의 그래프를 그릴 수 있다.

import numpy as np
import matplotlib.pyplot as plt

def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)

t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)

plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')

plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

plt.figure()와 plt.subplot()은 현재 어느 위치에서 그래프를 그릴 것인지, 어떤 그래프를 조작할지 선언하는 함수이다. plt.subplot(lmn)은 l개의 행과 m개의 열로 이루어진 subplot에서 n번째 칸에 그래프를 그릴 것임을 선언하는 함수이다. subplot끼리 축을 공유하는 것도 가능하다[3].

subplot의 위치와 여백을 조절하고 싶다면, GridSpec을 사용해 조절할 수 있다[4].

ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))

3. 축에 문자열 삽입하기
다음과 같이 축에 문자열을 삽입할 수 있다. rotation에 각도를 주어 회전 각도를 설정할 수 있다[5].

"""
Demo of custom tick-labels with user-defined rotation.
"""
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)
plt.show()

4. 그래프에서 x축의 tick mark 제거하기[6]

"""
Demo of custom tick-labels with user-defined rotation.
"""
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']

plt.plot(x, y, 'ro')
# You can specify a rotation for the tick labels in degrees or with keywords.
plt.xticks(x, labels, rotation='vertical')
# Pad margins so that markers don't get clipped by the axes
plt.margins(0.2)
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=0.15)

plt.tick_params( axis='x', which='major', bottom='off', top='off' )

plt.show()

without-tick-mark

5. Tick label 조절하기

import scipy as sp
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec

x = sp.linspace(-200,200,128) # arbitary x data
y1 = sp.exp(-(x/50)**2)       # arbitary y1 data

fig1 = plt.figure(figsize=[4,3])
gs = GridSpec(1,1,bottom=0.18,left=0.18,right=0.82)
ax = fig1.add_subplot(gs[0,0])

line1 = ax.plot(x,y1,linewidth=2, color=[68.0/255,78.0/255,154.0/255])

ax.set_xlabel('x data')
ax.set_ylabel('y1 data')

plt.show()

위의 코드로 그린 그래프는 tick label이 너무 좁게 표현되어 있다.

import scipy as sp
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec

x = sp.linspace(-200,200,128)
y1 = sp.exp(-(x/50)**2)      

fig1 = plt.figure(figsize=[4,3])
gs = GridSpec(1,1,bottom=0.18,left=0.18,right=0.82)
ax = fig1.add_subplot(gs[0,0])

line1 = ax.plot(x,y1,linewidth=2, color=[68.0/255,78.0/255,154.0/255])

ax.set_xlabel('x data')
ax.set_ylabel('y1 data')

# Changing the label's font-size
ax.tick_params(axis='x', labelsize=8)

plt.show()


폰트 크기를 조절했지만, 여전히 보기에 불편하다.

import scipy as sp
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec

x = sp.linspace(-200,200,128)
y1 = sp.exp(-(x/50)**2)      

fig1 = plt.figure(figsize=[4,3])
gs = GridSpec(1,1,bottom=0.18,left=0.18,right=0.82)
ax = fig1.add_subplot(gs[0,0])

line1 = ax.plot(x,y1,linewidth=2, color=[68.0/255,78.0/255,154.0/255])

ax.set_xlabel('x data')
ax.set_ylabel('y1 data')

# Setting the x-axis major tick's location
ax.set_xticks([-200,-150,-100,-50,0,50,100,150,200])

# Setting the x-axis major tick's label
ax.set_xticklabels(['-200','','-100','','Zero', '','100','','200'])

plt.show()

x축의 tick label을 수정함으로써 보기에 편리한 그래프를 그릴 수 있다.

6. Bar chart 그리기

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

7. 그래프에 vertical/horizontal line 삽입하기[8]

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
                ha='center', va='bottom')

axhline(y=5.,color='k',ls='dashed')
axvline(x=1.75,color='k',ls='dashed')

autolabel(rects1)
autolabel(rects2)

plt.show()

insertLine

8. 그래프를 eps 형식으로 저장하기
그래프를 eps 형식으로 저장하고 싶다면, savefig 함수를 호출하면 된다[9].

plt.savefig('destination_path.eps', format='eps', dpi=1000)

9. Customizing matplotlib
matplotlib은 .config/matplotlib/matplotlibrc 파일을 읽어 초기화하며, 이 파일을 수정해 matplotlib을 customize할 수 있다[10].

– matplotlib 빠르게 사용하기 : pyplot에 익숙하지 않다면 examplegallery에서 예제 코드를 확인해 빠르게 그래프를 그리는 것도 한 가지 방법이 될 수 있다[11, 12].

Matplotlib is the whole package; matplotlib.pyplot is a module in matplotlib; and pylab is a module that gets installed alongside matplotlib.

– matplotlib, pyplot 그리고 pylab의 관계 : matplotlib은 pyplot을 포함하는 패키지이고, pylab은 matplotlib과 함께 설치되는 모듈이다. pylab은 pyplot과 matplotlib.pyplot과 numpy를 하나의 namespace로 묶어준다[13].

References:
[1] matplotlib, http://matplotlib.org/index.html
[2] Beginner’s Guide, matplotlib, http://matplotlib.org/users/beginner.html
[3] pylab_examples example code: subplots_demo.py, matplotlib, http://matplotlib.org/examples/pylab_examples/subplots_demo.html#pylab-examples-subplots-demo
[4] Customizing Location of Subplot Using GridSpec, matplotlib, http://matplotlib.org/users/gridspec.html
[5] ticks_and_spines example code: ticklabels_demo_rotation.py, matplotlib, http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html
[6] Modifying the tick-labels, Works of Science, http://worksofscience.net/matplotlib/tick_labels
[7] api example code: barchart_demo.py, matplotlib, http://matplotlib.org/1.4.2/examples/api/barchart_demo.html
[8] pylab_examples example code: axhspan_demo.py, matplotlib, http://matplotlib.org/1.4.2/examples/pylab_examples/axhspan_demo.html
[9] How-To, matplotlib, http://matplotlib.org/faq/howto_faq.html
[10] Customizing matplotlib, matplotlib, http://matplotlib.org/users/customizing.html
[11] Matplotlib Examples, matplotlib, http://matplotlib.org/examples/index.html
[12] Gallery, matplotlib, http://matplotlib.org/gallery.html
[13] Matplotlib, pyplot and pylab: how are they related?, matplotlib, http://matplotlib.org/faq/usage_faq.html#matplotlib-pyplot-and-pylab-how-are-they-related

Advertisements
Tagged with: , , ,
Posted in 2) Computer Engineering
One comment on “matplotlib
  1. […] 그릴 때 되도록이면 pyplot을 사용하고 싶지만, 우리 연구실에서 jgraph를 쓰므로 jgraph의 사용법을 […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

누적 방문자 수
  • 98,786 hits
%d bloggers like this: