matplotlib 是python最著名的绘图库,它提供了一整套和matlab类似的命令API,十分适合交互式地进行制图。并且也能够方便地将它做为绘图控件,嵌入GUI应用程序中。css
它的文档至关完备,而且 Gallery页面 中有上百幅缩略图,打开以后都有源程序。所以若是你须要绘制某种类型的图,只须要在这个页面中浏览/复制/粘贴一下,基本上都能搞定。html
在Linux下比较著名的数据图工具还有gnuplot,这个是免费的,Python有一个包能够调用gnuplot,可是语法比较不习惯,并且画图质量不高。java
而 Matplotlib则比较强:Matlab的语法、python语言、latex的画图质量(还可使用内嵌的latex引擎绘制的数学公式)。python
matplotlib的pyplot子库提供了和matlab相似的绘图API,方便用户快速绘制2D图表。例子:linux
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 , 2014
python 科学计算学习:numpy快速处理数据测试
@author : 皮皮
'' '
import string
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__' :
file = open(E:machine_learningdatasetshousing_datahousing_data_ages.txt, 'r' )
linesList = file.readlines()
# print(linesList)
linesList = [line.strip().split(,) for line in linesList]
file.close()
print(linesList:)
print(linesList)
# years = [string.atof(x[ 0 ]) for x in linesList]
years = [x[ 0 ] for x in linesList]
print(years)
price = [x[ 1 ] for x 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(* 2000 yuan))
plt.ylim( 0 , 15 )
plt.title( 'line_regression & gradient decrease' )
plt.legend()
plt.show()
|
matplotlib中的快速绘图的函数库能够经过以下语句载入:web
1
|
import matplotlib.pyplot as plt
|
pylab模块express
matplotlib还提供了名为pylab的模块,其中包括了许多numpy和pyplot中经常使用的函数,方便用户快速进行计算和绘图,能够用于IPython中的快速交互式使用。canvas
接下来调用figure建立一个绘图对象,而且使它成为当前的绘图对象。数组
1
|
plt.figure(figsize=( 8 , 4 ))
|
也能够不建立绘图对象直接调用接下来的plot函数直接绘图,matplotlib会为咱们自动建立一个绘图对象。若是须要同时绘制多幅图表的话,能够是给figure传递一个整数参数指定图标的序号,若是所指定序号的绘图对象已经存在的话,将不建立新的对象,而只是让它成为当前绘图对象。app
经过figsize参数能够指定绘图对象的宽度和高度,单位为英寸;dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80。所以本例中所建立的图表窗口的宽度为8*80 = 640像素。
可是用工具栏中的保存按钮保存下来的png图像的大小是800*400像素。这是由于保存图表用的函数savefig使用不一样的DPI配置,savefig函数也有一个dpi参数,若是不设置的话,将使用matplotlib配置文件中的配置,此配置能够经过以下语句进行查看:
1
2
3
|
>>> import matplotlib
>>> 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以后,用关键字参数指定各类属性:
第二句直接经过第三个参数b--指定曲线的颜色和线型,这个参数称为格式化参数,它可以经过一些易记的符号快速指定曲线的样式。其中b表示蓝色,--表示线型为虚线。
在IPython中输入 plt.plot? 能够查看格式化字符串的详细配置。
接下来经过一系列函数设置绘图对象的各个属性:
1
2
3
4
5
|
plt.xlabel(years(+ 2000 ))
plt.ylabel(housing average price(* 2000 yuan))
plt.ylim( 0 , 15 )
plt.title( 'line_regression & gradient decrease' )
plt.legend()
|
最后调用plt.show()显示出咱们建立的全部绘图对象。
matplotlib所绘制的图的每一个组成部分都对应有一个对象,咱们能够经过调用这些对象的属性设置方法set_*或者pyplot的属性设置函数setp设置其属性值。例如plot函数返回一个 matplotlib.lines.Line2D 对象的列表,下面的例子显示如何设置Line2D对象的属性:
1
2
3
4
5
6
|
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x = np.arange( 0 , 5 , 0.1 )
>>> line, = plt.plot(x, x*x) # plot返回一个列表,经过line,获取其第一个元素
>>> # 调用Line2D对象的set_*方法设置属性值
>>> line.set_antialiased(False)
|
1
2
3
4
|
>>> # 同时绘制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函数获取对象的属性值:
1
2
3
4
5
6
7
8
9
10
|
>>> line.get_linewidth()
1.0
>>> plt.getp(lines[ 0 ], color) # 返回color属性
'r'
>>> plt.getp(lines[ 1 ]) # 输出所有属性
alpha = 1.0
animated = False
antialiased or aa = True
axes = Axes( 0.125 , 0.1 ; 0 .775x0. 8 )
... ...
|
注意getp函数只能对一个对象进行操做,它有两种用法:
matplotlib的整个图表为一个Figure对象,此对象在调用plt.figure函数时返回,咱们也能够经过plt.gcf函数获取当前的绘图对象:
1
2
3
4
5
|
>>> f = plt.gcf()
>>> plt.getp(f)
alpha = 1.0
animated = False
...
|
Figure对象有一个axes属性,其值为AxesSubplot对象的列表,每一个AxesSubplot对象表明图表中的一个子图,前面所绘制的图表只包含一个子图,当前子图也能够经过plt.gca得到:
1
2
3
4
5
|
>>> plt.getp(f, axes)
[<matplotlib.axes.axessubplot 0x05cdd170 = "" at= "" object= "" >]
>>> plt.gca()
<matplotlib.axes.axessubplot 0x05cdd170 = "" at= "" object= "" >
</matplotlib.axes.axessubplot></matplotlib.axes.axessubplot>
|
用plt.getp能够发现AxesSubplot对象有不少属性,例如它的lines属性为此子图所包括的 Line2D 对象列表:
1
2
3
4
5
6
|
>>> alllines = plt.getp(plt.gca(), lines)
>>> alllines
>>> alllines[ 0 ] == line # 其中的第一条曲线就是最开始绘制的那条曲线
True
|
经过这种方法咱们能够很容易地查看对象的属性和它们之间的包含关系,找到须要配置的属性。
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()快速绘制包含多个子图的图表,它的调用形式以下:
1
2
|
subplot(numRows, numCols, plotNum)
|
若是须要同时绘制多幅图表,能够给figure()传递一个整数参数指定Figure对象的序号,若是序号所指定的Figure对象已经存在,将不建立新的对象,而只是让它成为当前的Figure对象。
1
2
|
import numpy as np
|
1
2
|
import matplotlib.pyplot as plt
|
1
|
|
1
2
|
plt.figure( 1 ) # 建立图表 1
|
1
2
|
plt.figure( 2 ) # 建立图表 2
|
1
2
|
ax1 = plt.subplot( 211 ) # 在图表 2 中建立子图 1
|
1
2
|
ax2 = plt.subplot( 212 ) # 在图表 2 中建立子图 2
|
1
|
|
1
2
|
x = np.linspace( 0 , 3 , 100 )
|
1
2
|
for i in xrange( 5 ):
|
1
2
|
plt.figure( 1 ) #? # 选择图表 1
|
1
2
|
plt.plot(x, np.exp(i*x/ 3 ))
|
1
2
|
plt.sca(ax1) #? # 选择图表 2 的子图 1
|
1
2
|
plt.plot(x, np.sin(i*x))
|
1
2
|
plt.sca(ax2) # 选择图表 2 的子图 2
|
1
2
|
plt.plot(x, np.cos(i*x))
|
1
|
|
1
2
|
plt.show()
|
matplotlib的缺省配置文件中所使用的字体没法正确显示中文。为了让图表能正确显示中文,能够有几种解决方案。
比较简便的方式是,中文字符串用unicode格式,例如:u''测试中文显示'',代码文件编码使用utf-8 加上 # coding = utf-8 一行。
matplotlib API包含有三层,Artist层处理全部的高层结构,例如处理图表、文字和曲线等的绘制和布局。一般咱们只和Artist打交道,而不须要关心底层的绘制细节。
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 (主要讲面向对象绘图,对于新手可能有点乱)
1
2
|
>>> import pylab 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值的直线)
1
2
|
import numpy as np
|
1
2
|
import pylab as pl
|
1
|
|
1
2
|
x = [ 1 , 2 , 3 , 4 , 5 ]# Make an array of x values
|
1
2
|
y = [ 1 , 4 , 9 , 16 , 25 ]# Make an array of y values for each x value
|
1
|
|
1
2
|
pl.plot(x, y)# use pylab to plot x and y
|
1
|
pl.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
1
2
|
import numpy as np
|
1
2
|
import pylab as pl
|
1
|
|
1
2
|
x = [ 1 , 2 , 3 , 4 , 5 ]# Make an array of x values
|
1
2
|
y = [ 1 , 4 , 9 , 16 , 25 ]# Make an array of y values for each x value
|
1
2
|
pl.plot(x, y)# use pylab to plot x and y
|
1
|
|
1
2
|
pl.title(’Plot of y vs. x’)# give plot a title
|
1
2
|
pl.xlabel(’x axis’)# make axis labels
|
1
2
|
pl.ylabel(’y axis’)
|
1
|
|
1
2
|
pl.xlim( 0.0 , 7.0 )# set axis limits
|
1
2
|
pl.ylim( 0.0 , 30 .)
|
1
|
|
1
|
pl.show()# show the plot on the screen
|
2.2.5 在一个坐标系上绘制多个图 Plotting more than one plot on the same set of axes
1
2
|
import numpy as np
|
1
2
|
import pylab as pl
|
1
|
|
1
2
|
x1 = [ 1 , 2 , 3 , 4 , 5 ]# Make x, y arrays for each graph
|
1
2
|
y1 = [ 1 , 4 , 9 , 16 , 25 ]
|
1
2
|
x2 = [ 1 , 2 , 4 , 6 , 8 ]
|
1
2
|
y2 = [ 2 , 4 , 8 , 12 , 16 ]
|
1
|
|
1
2
|
pl.plot(x1, y1, ’r’)# use pylab to plot x and y
|
1
2
|
pl.plot(x2, y2, ’g’)
|
1
|
|
1
2
|
pl.title(’Plot of y vs. x’)# give plot a title
|
1
2
|
pl.xlabel(’x axis’)# make axis labels
|
1
2
|
pl.ylabel(’y axis’)
|
1
|
|
1
|
|
1
2
|
pl.xlim( 0.0 , 9.0 )# set axis limits
|
1
2
|
pl.ylim( 0.0 , 30 .)
|
1
|
|
1
|
|
1
|
pl.show()# show the plot on the screen
|
pl.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=
1
2
|
import numpy as np
|
1
2
|
import pylab as pl
|
1
|
|
1
2
|
x1 = [ 1 , 2 , 3 , 4 , 5 ]# Make x, y arrays for each graph
|
1
2
|
y1 = [ 1 , 4 , 9 , 16 , 25 ]
|
1
2
|
x2 = [ 1 , 2 , 4 , 6 , 8 ]
|
1
2
|
y2 = [ 2 , 4 , 8 , 12 , 16 ]
|
1
|
|
1
2
|
plot1 = pl.plot(x1, y1, ’r’)# use pylab to plot x and y : Give your plots names
|
1
2
|
plot2 = pl.plot(x2, y2, ’go’)
|
1
|
|
1
2
|
pl.title(’Plot of y vs. x’)# give plot a title
|
1
2
|
pl.xlabel(’x axis’)# make axis labels
|
1
2
|
pl.ylabel(’y axis’)
|
1
|
|
1
|
|