首页 > 技术文章 > Python之matplotlib学习(一)

gsblog 2013-11-13 20:31 原文

小试牛刀

在上一节已经安装好matplotlib模块,下面使用几个例子熟悉一下。

对应的一些文档说明:

http://matplotlib.org/1.3.1/api/pyplot_summary.html

例子1:二维坐标——整数

[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')

输出结果:

上图的例子可以看到直线不平滑,原因在于样本点太少的缘故。

例子2:二维坐标——浮点数

[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特有的。

输出结果:

例子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》

推荐阅读