2011年11月9日 星期三

[Python]畫圖表的好工具 - Matplotlib


碩班要寫論文時常常會需要畫一堆圖表,由於我不太會用Excel於是就選擇Python + Matplotlib來當做我畫圖表的工具。

http://matplotlib.sourceforge.net/
Matplotlib是Python一套功能很強大的畫圖表Library

http://matplotlib.sourceforge.net/gallery.html
上面連結是畫出來的一些範例,基本上所有圖表都可以畫得出來。就算你要自創一個圖表也很簡單,只要自己加進去就好了,因為是他是open source。


  • 以下提供一些簡單的範例,有興趣的讀者可以去查官網上的文件。



#!/usr/bin/env python
"""

Demonstrate how to do two plots on the same axes with different left
right scales.


The trick is to use *2 different axes*.  Turn the axes rectangular
frame off on the 2nd axes to keep it from obscuring the first.
Manually set the tick locs and labels as desired.  You can use
separate matplotlib.ticker formatters and locators as desired since
the two axes are independent.

This is achieved in the following example by calling the Axes.twinx()
method, which performs this work. See the source of twinx() in
axes.py for an example of how to do it for different x scales. (Hint:
use the xaxis instance and call tick_bottom and tick_top in place of
tick_left and tick_right.)

The twinx and twiny methods are also exposed as pyplot functions.

"""

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')


ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')
plt.show()

  • 底下是一個長條圖的範例



#!/usr/bin/env python  
import numpy.numarray as na
from pylab import *

#draw plot
labels = ["sample1", "sample2", "sample3"]
size =   [659, 2659, 32384]

x1 = na.array(range(3))*0.9+0.5
x2 = na.array(range(3))*0.9+1.0
x3 = na.array(range(3))*0.9+2.0

#draw bar
width = 0.2
b1 = bar(x1, size, width=width, color = 'c')

#draw tick
yticks(range(0,33000,5000))
xticks(x1+0.1, labels)

#label Y axis
ylabel('Y axis', fontsize=12, fontweight='bold')

xlim(0, x3[1])
ylim(0,33000)
title("This is an example to draw the bar chart",fontsize=12, fontweight='bold')
gca().get_xaxis().tick_bottom()
gca().get_yaxis().tick_left()

savefig('bar_chart.png')
savefig('bar_chart.pdf')
show()

  • 複雜一點的圖形也可以輕易畫出來,以下是一個簡單的範例



#!/usr/bin/env python  
from pylab import *

tmp = 1048576 * 0.0053
xary = [i for i in range(8,512,8)]
yary = [((tmp + 1048576 / i * 0.45)/1000*88) for i in range(8,512,8)]

x2ary = [i for i in range(8,512,8)]
y2ary = [((1048576 / i * 0.0875)+(1048576 * 0.0003223)) for i in range(8,512,8)]
figure(num=None, figsize=(8, 5), dpi=80, facecolor='w', edgecolor='k')
ax1 = subplot(111)
p1 = ax1.plot(xary,yary,'ro')
ax1.set_xlabel('Title1',fontsize=16, fontweight='bold')
ax1.set_ylabel('ylabel1',fontsize=16, fontweight='bold', color='r')
ax2 = twinx()
p2 = ax2.plot(x2ary, y2ary, 'bv')
ax2.set_ylabel('ylabel2',fontsize=16, fontweight='bold', color='g')
title('Title2',fontsize=16, fontweight='bold')
lines = [p1, p2]
legend(lines, ("Test1", "Test2"), shadow=True, numpoints=1)
grid(True)
show()

沒有留言:

張貼留言