小試牛刀html
在上一節已經安裝好matplotlib模塊,下面使用幾個例子熟悉一下。python
對應的一些文檔說明:api
http://matplotlib.org/1.3.1/api/pyplot_summary.htmlspa
例子1:二維座標——整數3d
[root@typhoeus79 20131113]# ipython
In [1]: import matplotlib.pyplot as plt In [2]: x = range(6) In [3]: plt.plot(x,[xi*xi for xi in x]) Out[3]: [<matplotlib.lines.Line2D at 0x1cf4050>] In [4]: plt.savefig('test1.png')
輸出結果:code
上圖的例子能夠看到直線不平滑,緣由在於樣本點太少的緣故。htm
例子2:二維座標——浮點數blog
[root@typhoeus79 20131113]# ipython
In [1]: import matplotlib.pyplot as plt
In [2]: import numpy as np In [3]: x = np.arange(0.0,6.0,0.1) In [4]: plt.plot(x,[xi * xi for xi in x]) Out[4]: [<matplotlib.lines.Line2D at 0x1cf1f10>] In [5]: plt.savefig('test2.png')
range以及xrange是python中有的,而arange是numpy特有的。ip
輸出結果:文檔
例子3:二維座標——多個曲線
[root@typhoeus79 20131113]# ipython
In [1]: import matplotlib.pyplot as plt
In [2]: import numpy as np In [4]: x = range(5) In [5]: x Out[5]: [0, 1, 2, 3, 4] In [6]: plt.plot(x,[xi * 1.5 for xi in x]) Out[6]: [<matplotlib.lines.Line2D at 0x1cf2c50>] In [7]: plt.plot(x,[xi * 3.0 for xi in x]) Out[7]: [<matplotlib.lines.Line2D at 0x1cf2ed0>] In [8]: plt.plot(x,[xi / 3.0 for xi in x]) Out[8]: [<matplotlib.lines.Line2D at 0x1cf5590>] In [9]: plt.savefig('test3.png')
輸出結果:
例子4:二維座標——多個曲線,改進版本
In [1]: import matplotlib.pyplot as plt In [2]: import numpy as np In [3]: x = range(1,5) In [4]: plt.plot(x,[xi * 1.5 for xi in x],x,[xi * 3.0 for xi in x],x,[xi / 3.0 for xi in x]) Out[4]: [<matplotlib.lines.Line2D at 0x1cf3150>, <matplotlib.lines.Line2D at 0x1cf33d0>, <matplotlib.lines.Line2D at 0x1cf3a90>] In [5]: plt.savefig('test4.png')
多個數據使用一個plot進行輸出
例子5:二維座標——多個曲線,使用numpy進行改進
In [1]: import matplotlib.pyplot as plt In [2]: import numpy as np
In [3]: x = np.arange(1,5) In [4]: plt.plot(x,x*1.5,x,x*3.0,x,x/3.0) Out[4]: [<matplotlib.lines.Line2D at 0x1cf1fd0>, <matplotlib.lines.Line2D at 0x1cf4290>, <matplotlib.lines.Line2D at 0x1cf4950>] In [5]: plt.savefig('test5.png')
《Getting Started with Matplotlib》