Raster Graphic format with lossy compression method for photographic output.
PDF
Vector Portable Document Format (PDF).
PNG
Raster Portable Network Graphics (PNG), a raster graphics format with a lossless compression method (more adaptable to line art than JPG).
PS
Vector Language widely used in publishing and as printers jobs format.
SVG
Vector Scalable Vector Graphics (SVG), XML based.
支持的后端
Backend
Description
GTKAgg
GTK+ (The GIMP ToolKit GUI library) canvas with AGG rendering.
GTK
GTK+ canvas with GDK rendering. GDK rendering is rather primitive, and doesn’t include anti-aliasing for the smoothing of lines.
GTKCairo
GTK+ canvas with Cairo rendering.
WxAgg
wxWidgets (cross-platform GUI and tools library for GTK+, Windows, and Mac OS X. It uses native widgets for each operating system, so applications will have the look and feel that users expect on that operating system) canvas with AGG rendering.
WX
wxWidgets canvas with native wxWidgets rendering.
TkAgg
Tk (graphical user interface for Tcl and many other dynamic languages) canvas with AGG rendering.
QtAgg
Qt (cross-platform application framework for desktop and embedded development) canvas with AGG rendering (for Qt version 3 and earlier).
Qt4Agg
Qt4 canvas with AGG rendering.
FLTKAgg
FLTK (cross-platform C++ GUI toolkit for UNIX/Linux (X11), Microsoft Windows, and Mac OS X) canvas with Agg rendering.
渲染器的输出格式为:
渲染器
文件类型
AGG
.png
PS
.eps or .ps
PDF
.pdf
SVG
.svg
Cairo
.png, .ps, .pdf, .svg
GDK
.png, .jpg
python-dateutil - 增强datetime
可以使用的集成环境IDE
Enthought Python Distribution
Python(x,y)
Sage
Anaconda
开始使用 Matplotlib
三种使用Matplotlib的方式
pyplot: 提供与Matlab类似的函数式环境,state-machine interface。通常用于interactive ploting的模式,例如ipython,可立即看到绘图结果。使用方式如下:from matplotlib import pyplot as plt,pyplot中提供的函数接口见:http://matplotlib.org/api/pyplot_api.html#pyplot
import matplotlib.pyplot as plt import numpy as np
len = 10
x = [] y = [] z = [] m = [] n = []
xx = range(len) for i in range(len): x.append(np.random.rand()) y.append(np.random.rand()) z.append(np.random.rand()) m.append(np.random.rand()) n.append(np.random.rand())
# Using different line styles plt.plot(xx,x,'o',label='x') plt.plot(xx,y,'^',label='y') plt.plot(xx,z,'x',label='z') plt.plot(xx,m,'s',label='z') plt.plot(xx,n,'D',label='z') plt.legend()
import matplotlib.pyplot as plt import numpy as np
len = 10
x = [] y = [] z = [] m = []
xx = range(len) for i inrange(len): x.append(np.random.rand()) y.append(np.random.rand()) z.append(np.random.rand()) m.append(np.random.rand())
# Using different line styles plt.plot(xx,x,'--o',label='x') plt.plot(xx,y,'-.^',label='y') plt.plot(xx,z,'-x',label='z') plt.plot(xx,m,':s',label='z') plt.legend()
plt.grid(True) plt.xlabel('Points') plt.ylabel('Random Value') plt.title('Line with Markers')
import matplotlib.pyplot as plt import numpy as np
theta = np.arange(0.,2.,1./180.)*np.pi
# Draw a spiral plt.polar(3*theta,theta/5) # Draw a polar rose, a pretty function that resembles a flower plt.polar(theta,np.cos(8*theta)) # Draw a circular plt.polar(theta,[1.4]*len(theta))
plt.title('Polar Plot')
plt.show()
效果图
可以通过参数rgrids和thetagrid来控制相关的参数显示,比如下面的代码将绘制一个蝴蝶。
rgrids的参数有下面几个:
radii:The radial distances at which the grid lines should be drawn.
labels: The labels to display at radii grid. By default, the values from radii would be used, but if not None, then it has to be of the same length as that of radii.
angle: The angle at which the labels are displayed (by default it’s 22.5°).
thetagrids的参数有下面几个:
angles: label的位置
labels: Specifies the labels to be printed at given angles. If None, then the angles values are used, or else the array must be of the same length of angles.
frac: The polar axes radius fraction at which we want the label to be drawn (1 is the edge, 1.1 is outside, and 0.9 is inside).
import matplotlib.pyplot as plt import numpy as np
x = np.arange(0,4*np.pi,.01) y = np.sin(x)
plt.plot(x,y)
plt.text(0.1,-0.05,'Sin(x)') plt.figtext(0.5,.5,'sin(x) center') plt.annotate('This point must be really \nmean something',xy=(np.pi/2.,1),xytext=(2.9,0.7), arrowprops=dict(facecolor='cyan',shrink=0.05))
for i,style in enumerate(arrstyles): plt.annotate(style,xytext=(1,2+2*i),xy=(4,1+2*i),arrowprops=dict(arrowstyle=style))
for i,style in enumerate(arrstyles): plt.annotate('',xytext=(6,2+2*i),xy=(8,1+2*i),arrowprops=dict(arrowstyle=style))
plt.title('Different Arrows')
plt.show()
效果图
Matplotlib 进阶
使用Matplotlib的几种方式
有三种使用Matplotlib的方法:
pyplot
pylab:将Matplotlib和NumPy集合在一起,很像Matlab
面向对象的方式:这也是最好的一种方式,因为可以对返回的结果进行全方位的控制
同一个程序用上面的三种方法,效果图如下所示:
源码如下所示:
pyplot
1 2 3 4 5 6 7
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 10, 0.1) y = np.random.randn(len(x)) plt.plot(x, y) plt.title('random numbers') plt.show()
pylab
使用ipython -pylab,输入代码如下:
1 2 3 4 5 6
In [1]: x = arange(0, 10, 0.1) In [2]: y = randn(len(x)) In [3]: plot(x, y) Out[3]: [<matplotlib.lines.Line2D object at 0x4284dd0>] In [4]: title('random numbers') In [5]: show()
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 10, 0.1) y = np.random.randn(len(x)) fig = plt.figure() ax = fig.add_subplot(111) l, = plt.plot(x, y) t = ax.set_title('random numbers') plt.show()
对比
从上面的代码来看,pylab模式下的代码最少,pyplot次之,面向对象的代码最多。
正如python之禅所说:”Explicit is better than implicit” ,”Simple is better than complex” 。 在简单的交互模式下,pylab或者pyplot是最好的选择,因为他们隐藏了很多复杂性,但是如果我们需要更深一步的控制, 面向对象的API此时就会派上用场了,因为OO模式会清晰地告诉我们从哪里来,到哪里去。 特别是再将Matplotlib嵌入到GUI的时候更是如此。
from matplotlib.figure import Figure :这里的Figure是我们绘图的后端独立单元 from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas :这里的FigureCanvas使我们绘图的画布,并且除了是一个Matplotlib类外,还是一个QWidget类,所以可以直接继承使用。
import sys from PyQt4 import QtGui import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
classQt4MplCanvas(FigureCanvas): ''' Class to represent the FigureCanvas widget ''' def__init__(self): self.fig = Figure() self.axes = self.fig.add_subplot(111) self.x = np.arange(0.,3.,0.01) self.y = np.cos(2*np.pi*self.x) self.axes.plot(self.x,self.y)
# initialize the canvas where the Figure renders into FigureCanvas.__init__(self,self.fig)
import sys from PyQt4 import QtGui import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
classQt4MplCanvas(FigureCanvas): ''' Class to represent the FigureCanvas widget ''' def__init__(self,parent): self.fig = Figure() self.axes = self.fig.add_subplot(111) self.x = np.arange(0.,3.,0.01) self.y = np.cos(2*np.pi*self.x) self.axes.plot(self.x,self.y)
# initialize the canvas where the Figure renders into FigureCanvas.__init__(self,self.fig)