【Python开发】使用python中的matplotlib进行绘图分析数据
matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。
它的文档相当完备,并且 Gallery页面 中有上百幅缩略图,打开之后都有源程序。因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定。
在Linux下比较著名的数据图工具还有gnuplot,这个是免费的,Python有一个包可以调用gnuplot,但是语法比较不习惯,而且画图质量不高。
而 Matplotlib则比较强:Matlab的语法、python语言、latex的画图质量(还可以使用内嵌的latex引擎绘制的数学公式)。
快速绘图![\]()
matplotlib的pyplot子库提供了和matlab类似的绘图API,方便用户快速绘制2D图表。例子:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#
coding=gbk'''Created
on Jul 12,2014python
科学计算学习:numpy快速处理数据测试@author:
皮皮'''importstringimportmatplotlib.pyplot
as plt importnumpy
as npif__name__
== '__main__': file
= open(E:machine_learningdatasetshousing_datahousing_data_ages.txt, 'r') linesList
= file.readlines()#
print(linesList) linesList
= [line.strip().split(,) forline
in linesList] file.close() print(linesList:) print(linesList)#
years = [string.atof(x[0])forx
in linesList] years
= [x[0]forx
in linesList] print(years) price
= [x[1]forx
in linesList] print(price) plt.plot(years,
price, 'b*')#,label=$cos(x^2)$) plt.plot(years,
price, 'r') plt.xlabel(years(+2000)) plt.ylabel(housing
average price(*2000yuan)) plt.ylim(0,15) plt.title('line_regression
& gradient decrease') plt.legend() plt.show() |

matplotlib中的快速绘图的函数库可以通过如下语句载入:
|
1
|
importmatplotlib.pyplot
as plt |
pylab模块
matplotlib还提供了名为pylab的模块,其中包括了许多numpy和pyplot中常用的函数,方便用户快速进行计算和绘图,可以用于IPython中的快速交互式使用。
接下来调用figure创建一个绘图对象,并且使它成为当前的绘图对象。
|
1
|
plt.figure(figsize=(8,4)) |
也可以不创建绘图对象直接调用接下来的plot函数直接绘图,matplotlib会为我们自动创建一个绘图对象。如果需要同时绘制多幅图表的话,可以是给figure传递一个整数参数指定图标的序号,如果所指定序号的绘图对象已经存在的话,将不创建新的对象,而只是让它成为当前绘图对象。
通过figsize参数可以指定绘图对象的宽度和高度,单位为英寸;dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80。因此本例中所创建的图表窗口的宽度为8*80 = 640像素。
但是用工具栏中的保存按钮保存下来的png图像的大小是800*400像素。这是因为保存图表用的函数savefig使用不同的DPI配置,savefig函数也有一个dpi参数,如果不设置的话,将使用matplotlib配置文件中的配置,此配置可以通过如下语句进行查看:
|
1
2
3
|
>>>importmatplotlib>>>
matplotlib.rcParams[savefig.dpi]100 |
下面的两行程序通过调用plot函数在当前的绘图对象中进行绘图:
|
1
2
|
plt.plot(years,
price, 'b*')#,label=$cos(x^2)$)plt.plot(years,
price, 'r') |
plot函数的调用方式很灵活,第一句将x,y数组传递给plot之后,用关键字参数指定各种属性:
- label : 给所绘制的曲线一个名字,此名字在图示(legend)中显示。只要在字符串前后添加$符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。
- color : 指定曲线的颜色
- linewidth : 指定曲线的宽度
第二句直接通过第三个参数b--指定曲线的颜色和线型,这个参数称为格式化参数,它能够通过一些易记的符号快速指定曲线的样式。其中b表示蓝色,--表示线型为虚线。
在IPython中输入 plt.plot? 可以查看格式化字符串的详细配置。
接下来通过一系列函数设置绘图对象的各个属性:
12345plt.xlabel(years(+2000))plt.ylabel(housing average price(*2000yuan))plt.ylim(0,15)plt.title('line_regression & gradient decrease')plt.legend()- xlabel : 设置X轴的文字
- ylabel : 设置Y轴的文字
- title : 设置图表的标题
- ylim : 设置Y轴的范围
- legend : 显示图示
最后调用plt.show()显示出我们创建的所有绘图对象。
配置属性
![\]()
matplotlib所绘制的图的每个组成部分都对应有一个对象,我们可以通过调用这些对象的属性设置方法set_*或者pyplot的属性设置函数setp设置其属性值。例如plot函数返回一个 matplotlib.lines.Line2D 对象的列表,下面的例子显示如何设置Line2D对象的属性:
123456>>>importnumpy as np>>>importmatplotlib.pyplot as plt>>> x = np.arange(0,5,0.1)>>> line, = plt.plot(x, x*x) # plot返回一个列表,通过line,获取其第一个元素>>> # 调用Line2D对象的set_*方法设置属性值>>> line.set_antialiased(False)1234>>> # 同时绘制sin和cos两条曲线,lines是一个有两个Line2D对象的列表>>> lines = plt.plot(x, np.sin(x), x, np.cos(x)) #>>> # 调用setp函数同时配置多个Line2D对象的多个属性值>>> plt.setp(lines, color=r, linewidth=2.0)这段例子中,通过调用Line2D对象line的set_antialiased方法,关闭对象的反锯齿效果。或者通过调用plt.setp函数配置多个Line2D对象的颜色和线宽属性。
同样我们可以通过调用Line2D对象的get_*方法,或者plt.getp函数获取对象的属性值:
12345678910>>> line.get_linewidth()1.0>>> plt.getp(lines[0], color) # 返回color属性'r'>>> plt.getp(lines[1]) # 输出全部属性alpha =1.0animated = Falseantialiased or aa = Trueaxes = Axes(0.125,0.1;0.775x0.8)... ...注意getp函数只能对一个对象进行操作,它有两种用法:
- 指定属性名:返回对象的指定属性的值
- 不指定属性名:打印出对象的所有属性和其值
matplotlib的整个图表为一个Figure对象,此对象在调用plt.figure函数时返回,我们也可以通过plt.gcf函数获取当前的绘图对象:
12345>>> f = plt.gcf()>>> plt.getp(f)alpha =1.0animated = False...Figure对象有一个axes属性,其值为AxesSubplot对象的列表,每个AxesSubplot对象代表图表中的一个子图,前面所绘制的图表只包含一个子图,当前子图也可以通过plt.gca获得:
12345>>> plt.getp(f, axes)[<matplotlib.axes.axessubplot0x05cdd170=""at=""object="">]>>> plt.gca()<matplotlib.axes.axessubplot0x05cdd170=""at=""object=""></matplotlib.axes.axessubplot></matplotlib.axes.axessubplot>用plt.getp可以发现AxesSubplot对象有很多属性,例如它的lines属性为此子图所包括的 Line2D 对象列表:
123456>>> alllines = plt.getp(plt.gca(), lines)>>> alllines>>> alllines[0] == line # 其中的第一条曲线就是最开始绘制的那条曲线True通过这种方法我们可以很容易地查看对象的属性和它们之间的包含关系,找到需要配置的属性。
Python图表绘制:matplotlib绘图库入门
matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。
它的文档相当完备,并且Gallery页面中有上百幅缩略图,打开之后都有源程序。因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定。
在Linux下比较著名的数据图工具还有gnuplot,这个是免费的,Python有一个包可以调用gnuplot,但是语法比较不习惯,而且画图质量不高。
而 Matplotlib则比较强:Matlab的语法、python语言、latex的画图质量(还可以使用内嵌的latex引擎绘制的数学公式)。
matplotlib实际上是一套面向对象的绘图库,它所绘制的图表中的每个绘图元素,例如线条Line2D、文字Text、刻度等在内存中都有一个对象与之对应。
plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。
可以在Ipython中输入类似plt.plot??的命令查看pyplot模块的函数是如何对各种绘图对象进行包装的。
matplotlib所绘制的图表的每个组成部分都和一个对象对应,我们可以通过调用这些对象的属性设置方法set_*()或者pyplot模块的属性设置函数setp()设置它们的属性值。
因为matplotlib实际上是一套面向对象的绘图库,因此也可以直接获取对象的属性
绘制一幅图需要对许多对象的属性进行配置,例如颜色、字体、线型等等。我们在绘图时,并没有逐一对这些属性进行配置,许多都直接采用了matplotlib的缺省配置。
可以使用subplot()快速绘制包含多个子图的图表,它的调用形式如下:
12subplot(numRows, numCols, plotNum)如果需要同时绘制多幅图表,可以给figure()传递一个整数参数指定Figure对象的序号,如果序号所指定的Figure对象已经存在,将不创建新的对象,而只是让它成为当前的Figure对象。
12importnumpy as np12importmatplotlib.pyplot as plt112plt.figure(1) # 创建图表112plt.figure(2) # 创建图表212ax1 = plt.subplot(211) # 在图表2中创建子图112ax2 = plt.subplot(212) # 在图表2中创建子图2112x = np.linspace(0,3,100)12fori in xrange(5):12plt.figure(1) #? # 选择图表112plt.plot(x, np.exp(i*x/3))12plt.sca(ax1) #? # 选择图表2的子图112plt.plot(x, np.sin(i*x))12plt.sca(ax2) # 选择图表2的子图212plt.plot(x, np.cos(i*x))112plt.show()matplotlib的缺省配置文件中所使用的字体无法正确显示中文。为了让图表能正确显示中文,可以有几种解决方案。
- 在程序中直接指定字体。
- 在程序开头修改配置字典rcParams。
- 修改配置文件。
比较简便的方式是,中文字符串用unicode格式,例如:u''测试中文显示'',代码文件编码使用utf-8 加上 # coding = utf-8 一行。
matplotlib API包含有三层,Artist层处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和Artist打交道,而不需要关心底层的绘制细节。
- 创建Figure对象
- 用Figure对象创建一个或者多个Axes或者Subplot对象
- 调用Axies等对象的方法创建各种简单类型的Artists
import matplotlib.pyplot as plt
X1 = range(0, 50) Y1 = [num**2 for num in X1] # y = x^2 X2 = [0, 1] Y2 = [0, 1] # y = x
Fig.show() Fig.savefig(test.pdf)
《Python科学计算》(Numpy视频) matplotlib-绘制精美的图表(快速绘图)(面向对象绘图)(深入浅出适合系统学习)
什么是 Matplotlib (主要讲面向对象绘图,对于新手可能有点乱)
12>>>importpylab as pl>>> import numpy
>>> numpy.__version__>>> import matplotlib
>>> matplotlib.__version__2 两种常用图类型:Line and scatter plots(使用plot()命令), histogram(使用hist()命令)
2.1 折线图&散点图 Line and scatter plots
2.1.1 折线图 Line plots(关联一组x和y值的直线)
12importnumpy as np12importpylab as pl112x = [1,2,3,4,5]# Make an array of x values12y = [1,4,9,16,25]# Make an array of y valuesforeach x value112pl.plot(x, y)# use pylab to plot x and y1pl.show()# show the plot on the screen
把pl.plot(x, y)改成pl.plot(x, y, 'o')即可,下图的蓝色版本
2.2 美化 Making things look pretty
2.2.1 线条颜色 Changing the line color
红色:把pl.plot(x, y, 'o')改成pl.plot(x, y, ’or’)
2.2.2 线条样式 Changing the line style
2.2.3 marker样式 Changing the marker style
2.2.4 图和轴标题以及轴坐标限度 Plot and axis titles and limits
12importnumpy as np12importpylab as pl112x = [1,2,3,4,5]# Make an array of x values12y = [1,4,9,16,25]# Make an array of y valuesforeach x value12pl.plot(x, y)# use pylab to plot x and y112pl.title(’Plot of y vs. x’)# give plot a title12pl.xlabel(’x axis’)# make axis labels12pl.ylabel(’y axis’)112pl.xlim(0.0,7.0)# set axis limits12pl.ylim(0.0,30.)11pl.show()# show the plot on the screen2.2.5 在一个坐标系上绘制多个图 Plotting more than one plot on the same set of axes
12importnumpy as np12importpylab as pl112x1 = [1,2,3,4,5]# Make x, y arraysforeach graph12y1 = [1,4,9,16,25]12x2 = [1,2,4,6,8]12y2 = [2,4,8,12,16]112pl.plot(x1, y1, ’r’)# use pylab to plot x and y12pl.plot(x2, y2, ’g’)112pl.title(’Plot of y vs. x’)# give plot a title12pl.xlabel(’x axis’)# make axis labels12pl.ylabel(’y axis’)1112pl.xlim(0.0,9.0)# set axis limits12pl.ylim(0.0,30.)111pl.show()# show the plot on the screenpl.legend((plot1, plot2), (’label1, label2’), 'best’, numpoints=1)
其中第三个参数表示图例放置的位置:'best’‘upper right’, ‘upper left’, ‘center’, ‘lower left’, ‘lower right’.
如果在当前figure里plot的时候已经指定了label,如plt.plot(x,z,label=
cos(x2) ),直接调用plt.legend()就可以了哦。12importnumpy as np12importpylab as pl112x1 = [1,2,3,4,5]# Make x, y arraysforeach graph12y1 = [1,4,9,16,25]12x2 = [1,2,4,6,8]12y2 = [2,4,8,12,16]112plot1 = pl.plot(x1, y1, ’r’)# use pylab to plot x and y : Give your plots names12plot2 = pl.plot(x2, y2, ’go’)112pl.title(’Plot of y vs. x’)# give plot a title12pl.xlabel(’x axis’)# make axis labels12pl.ylabel(’y axis’)1112pl.xlim(0.0,9.0)# set axis limits12pl.ylim(0.0,30.)1112pl.legend([plot1, plot2], (’red line’, ’green circles’), ’best’, numpoints=1)# make legend1pl.show()# show the plot on the screen12importnumpy as np12importpylab as pl112# make an array of random numbers with a gaussian distribution with12# mean =5.012# rms =3.012# number of points =100012data = np.random.normal(5.0,3.0,1000)112# make a histogram of the data array12pl.hist(data)112# make plot labels12pl.xlabel(’data’)1pl.show()如果不想要黑色轮廓可以改为pl.hist(data, histtype=’stepfilled’)
2.3.1 自定义直方图bin宽度 Setting the width of the histogram bins manually
bins = np.arange(-5., 16., 1.) #浮点数版本的range
pl.hist(data, bins, histtype=’stepfilled’)3 同一画板上绘制多幅子图 Plotting more than one axis per canvas
如果需要同时绘制多幅图表的话,可以是给figure传递一个整数参数指定图标的序号,如果所指定
序号的绘图对象已经存在的话,将不创建新的对象,而只是让它成为当前绘图对象。f1 = pl.figure(1)
pl.subplot(221)
pl.subplot(222)
pl.subplot(212)pl.subplots_adjust(left=0.08, right=0.95, wspace=0.25, hspace=0.45)
4 绘制文件中的数据Plotting data contained in files
4.1 从Ascii文件中读取数据 Reading data from ascii files
读取文件的方法很多,这里只介绍一种简单的方法,更多的可以参考官方文档和NumPy快速处理数据(文件存取)。
numpy的loadtxt方法可以直接读取如下文本数据到numpy二维数组
**********************************************
**********************************************
12importnumpy as np12importpylab as pl112# Use numpy to load the data contained in the file12# ’fakedata.txt’ into a2-D array called data12data = np.loadtxt(’fakedata.txt’)112# plot the first column as x, and second column as y12pl.plot(data[:,0], data[:,1], ’ro’)12pl.xlabel(’x’)12pl.ylabel(’y’)12pl.xlim(0.0,10.)1pl.show()4.2 写入数据到文件 Writing data to a text file
写文件的方法也很多,这里只介绍一种可用的写入文本文件的方法,更多的可以参考官方文档。
12importnumpy as np12# Let’s make2arrays (x, y) which we will write to a file12# x is an array containing numbers0to10, with intervals of112x = np.arange(0.0,10.,1.)12# y is an array containing the values in x, squared12y = x*x12print ’x = ’, x12print ’y = ’, y112# Now open a file to write the data to12# ’w’ means openfor’writing’12file = open(’testdata.txt’, ’w’)12# loop over each line you want to write to file12fori in range(len(x)):12# make a stringforeach line you want to write12# ’ ’ means ’tab’123# ’’ means ’newline’12# ’str()’ means you are converting the quantity in brackets to a string type123txt = str(x[i]) + ’ ’ + str(y[i]) + ’’12# write the txt to the file12file.write(txt)12# Close your file12file.close()这部分是翻译自:Python Plotting Beginners Guide
Matlplotlib对LaTeX有一定的支持,如果记得使用raw字符串语法会很自然:
在matplotlib里面,可以使用LaTex的命令来编辑公式,只需要在字符串前面加一个“r”即可
import matplotlib.pyplot as plt
x = arange(1,1000,1)
r = -2
c = 5
y = [5*(a**r) for a in x]程序执行结果如图3所示,这实际上是一个power-law的例子,有兴趣的朋友可以继续google之。
再看一个《用Python做科学计算》中的简单例子,下面的两行程序通过调用plot函数在当前的绘图对象中进行绘图:
plt.plot(x,y,label=
sin(x) ,color=red,linewidth=2)
plt.plot(x,z,b--,label=cos(x2) )plot函数的调用方式很灵活,第一句将x,y数组传递给plot之后,用关键字参数指定各种属性:
- label : 给所绘制的曲线一个名字,此名字在图示(legend)中显示。只要在字符串前后添加$符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。
- color : 指定曲线的颜色
- linewidth : 指定曲线的宽度
Writing mathematical expressions
- Subscripts and superscripts
- Fractions, binomials and stacked numbers
- Radicals
- Fonts
- Custom fonts
- Accents
- Symbols
- Example
- usetex with unicode
- Postscript options
- Possible hangups
- Troubleshooting
- matplotlib.rcParams属性字典
- 想要它正常工作,在matplotlibrc配置文件中需要设置text.markup = tex。
- 如果你希望图表中所有的文字(包括坐标轴刻度标记)都是LaTeX'd,需要在matplotlibrc中设置text.usetex = True。如果你使用LaTeX撰写论文,那么这一点对于使图表和论文中其余部分保持一致是很有用的。
参考文献自动搜集管理完美攻略(图文版):Latex+Lyx+Zotero
在实际中,我们可能经常会用到对数坐标轴,这时可以用下面的三个函数来实现
- Gnuplot简介
- IBM:gnuplot 让您的数据可视化,Linux 上的数据可视化工具
- 利用Python绘制论文图片: Gnuplot,pylab
- matplotlib下载及API手册地址
- Screenshots:example figures
- Gallery:Click on any image to see full size image and source code
- matplotlib所使用的数学库numpy下载及API手册
IBM:基于 Python Matplotlib 模块的高质量图形输出(2005年的文章有点旧)
matplotlib技巧集(绘制不连续函数的不连续点;参数曲线上绘制方向箭头;修改缺省刻度数目;Y轴不同区间使用不同颜色填充的曲线区域。)
Python:使用matp绘制不连续函数的不连续点;参数曲线上绘制方向箭头;修改缺省刻度数目;Y轴不同区间使用不同颜色填充的曲线区域。lotlib绘制图表
from:http://blog.csdn.net/pipisorry/article/details/37742423
ref:matplotlib绘图库入门http://www.cnblogs.com/wei-li/archive/2012/05/23/2506940.html
http://sebug.net/paper/books/scipydoc/matplotlib_intro.html
使用 python Matplotlib 库绘图http://blog.csdn.net/daniel_ustc/article/details/9714163
barChart:http://www.cnblogs.com/qianlifeng/archive/2012/02/13/2350086.html
















浙公网安备 33010602011771号