研究了一下用 Python 畫圖的方式,最強大的莫過於 matplotlib,它能產出高品質的 2D 與 3D 圖形。先記錄下來,之後慢慢深入。
matplotlib 下載與 API 手冊:SourceForge 專案頁
數學函式庫 numpy:scipy.org
#!/usr/bin/env python
import matplotlib.pyplot as plt
plt.plot([10, 20, 30])
plt.xlabel('tiems')
plt.ylabel('numbers')
plt.show()
三行有效程式碼就能畫出一條折線,這是 matplotlib 最迷人的地方。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pylab import *
# make a square figure and axes
figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
savefig('D:\\pie.png')
show()
這裡有幾個實用參數:explode 讓某一片扇區「爆開」以突顯重點,autopct 控制百分比顯示格式,shadow 加上陰影,savefig 則直接把圖存成檔案而不只是顯示。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 1.01, 0.01)
s = np.sin(2*2*np.pi*t)
plt.fill(t, s*np.exp(-5*t), 'r')
plt.grid(True)
# 保存為PDF格式,也可保存為PNG等圖形格式
plt.savefig('D:\\test.pdf')
plt.show()
用 arange 產生等距取樣的時間序列,再對 sin 波乘上衰減因子 exp(-5t),就得到一個典型的阻尼振盪波形;fill 負責填色,grid 加上格線。
小結:matplotlib 的分工很清晰——pyplot 或 pylab 負責「畫」,numpy 負責「算」。把資料算好,剩下的就是挑一個合適的 plot 函式。中文字型與負號顯示是中文環境的常見難題,需要另外指定字型,這部分留待後續整理。