0%

Python开发者Matplotlib指南

Matplotlib 简介

至理名言:A picture is worth a thousand words

MatplotLib 支持交互和非交互的绘图,并且可以保持图像到PNG、PS和其他类型的文件。

支持的输出格式

Format Type Description
EPS Vector Encapsulated PostScript.
JPG 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的方式

  1. pyplot: 提供与Matlab类似的函数式环境,state-machine interface。通常用于interactive ploting的模式,例如ipython,可立即看到绘图结果。使用方式如下:from matplotlib import pyplot as plt,pyplot中提供的函数接口见:http://matplotlib.org/api/pyplot_api.html#pyplot
  2. pylab:结合了pyplot(用于作图)和numpy(用于数学计算)。在本书中被嫌弃。使用方式如下:ipython -pylab
  3. 面向对象式的

对于面向对象式的,比如下面的代码:

1
2
3
4
5
6
7
8
9
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()

用Matplotlib绘制第一幅图片

源码

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
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

len = 10

x = []
y = []
z = []
xx = range(len)
for i in range(len):
x.append(np.random.rand())
y.append(np.random.rand())
z.append(np.random.rand())

plt.plot(xx,x)
plt.plot(xx,y)
plt.plot(xx,z)

plt.show()

效果图

用Matplotlib绘制添加各种信息的图片

在前面的基础上添加上网格,坐标,坐标轴信息和标题等信息

源码

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
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

# Adding grid,axis,label,title on basic plot

import matplotlib.pyplot as plt
import numpy as np

len = 10

x = []
y = []
z = []
xx = range(len)
for i in range(len):
x.append(np.random.rand())
y.append(np.random.rand())
z.append(np.random.rand())

# legend method 1
plt.plot(xx,x)
plt.plot(xx,y)
plt.plot(xx,z)
plt.legend(['legend x','legend y','legend z'],loc='best')

# legend method 2
#plt.plot(xx,x,label='legend x')
#plt.plot(xx,y,label='legend y')
#plt.plot(xx,z,label='legend z')
#plt.legend()

plt.grid(True)
#plt.axis([-1,10,0,1.02])
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Test data')

plt.show()

效果图

保存图像到文件

1
plt.savefig('plot.png')

绘图键盘快捷键与功能

键盘快捷键 命令
h or r or home Home or Reset
c or left arrow or backspace 后退
v or right arrow 前进
p Pan or Zoom
o Zoom-to-rectangle
s 保存
f 全屏
hold x Constrain pan or zoom to x-axis
hold y Constrain pan or zoom to y-axis
hold ctrl Preserve aspect ratio
g 网格显示
l Toggle y-axis scale (log or linear)

进入matplotlib环境

1
ipython -pylab

在该命令下,

  • ion : 打开交互模式
  • ioff:关闭交互模式
  • draw:强制重绘

配置Matplotlib

全局配置文件 /etc/matplotlibrc

在该文件中我们可以看到backend : TkAgg,因为TkAgg不基于任何依赖,所以在大部分平台上都会正常工作,这也是因为python默认使用的就是Tk/Tcl。

几个小技巧

plt.hold() - 是否保留原来图像

plt.interactive(True) - 使能交互模式

plt.legend有几个位置,可以使用loc参数

String Code
best 0
upper right 1
upper left 2
lower left 3
lower right 4
right 5
center left 6
center right 7
lower center 8
upper center 9
center 10

绘图的美化

这一章用来美化绘图咯。

颜色选项

通过加上简单的一个参数就可以控制图片的线条颜色了。

源码

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
32
33
34
35
36
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

# Adding colors

import matplotlib.pyplot as plt
import numpy as np

len = 10

x = []
y = []
z = []

xx = range(len)
for i in range(len):
x.append(np.random.rand())
y.append(np.random.rand())
z.append(np.random.rand())

# Adding color parameters
plt.plot(xx,x,'y',label='legend x')
plt.plot(xx,y,'m',label='legend y')
plt.plot(xx,z,'c',label='legend z')
plt.legend()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Colors')

plt.show()

效果图

支持的颜色列表:

Color abbreviation Color Name
b blue 蓝色
c cyan 蓝绿色
g green 绿色
k black 黑色
m magenta 品红色
r red 红色
w white 白色
y yellow 黄色

颜色的表示方法除了用缩写,还可以使用颜色名字或者16进制的RGB代码,比如下面的三行代码效果是一样的。

1
2
3
plot(xx,x,'r')
plot(xx,x,'red')
plot(xx,x,'#FF0000')

线条类型

源码

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
32
33
34
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

len = 10

x = []
y = []
z = []

xx = range(len)
for i in range(len):
x.append(np.random.rand())
y.append(np.random.rand())
z.append(np.random.rand())

# Using different line styles
plt.plot(xx,x,'--',label='x')
plt.plot(xx,y,'-.',label='y')
plt.plot(xx,z,':',label='z')
plt.legend()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Colors')

plt.show()

效果图

线条类型表

类型缩写 类型
- 实线
虚线
-. 点划线
: 点线

点标记类型

源码

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
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

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()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Markers')

plt.show()

效果图

标记点类型

标记缩写 标记类型
.
, 像素
o
v 倒三角
^ 正三角
< 左三角
> 右三角
1 Tripod down marker
2 Tripod up marker
3 Tripod left marker
4 Tripod right marker
s Square marker
p Pentagon marker
* Star marker
h Hexagon marker
H Rotated hexagon marker
+ Plus marker
x Cross (x) marker
D Diamond marker
d Thin diamond marker
_ Horizontal line (hline symbol) marker

组合标记和线类型

其实颜色、线条类型以及点标记是可以组合使用的。

源码

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
32
33
34
35
36
37
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

len = 10

x = []
y = []
z = []
m = []

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())

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

plt.show()

效果图

使用关键词参数来更好地控制绘图

前面的格式化参数虽然很有用,但是还是有些缺点的,比如,不允许我们分别设置点和线的颜色。
所以这里就需要使用关键词参数了。

源码

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
32
33
34
35
36
37
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

len = 5

x = []
y = []
z = []
m = []

xx = range(len)
for i in range(len):
x.append(np.random.rand())
y.append(np.random.rand())
z.append(np.random.rand())

plt.plot(xx,x,color='blue',linestyle='dashdot',linewidth=2,marker='o',
markerfacecolor='red',markeredgecolor='black',label='x')
plt.plot(xx,y,color='green',linestyle='solid',linewidth=3,marker='s',
markerfacecolor='blue',markeredgecolor='red',label='y')
plt.plot(xx,z,color='cyan',linestyle=':',linewidth=2,marker='^',
markerfacecolor='green',markeredgecolor='blue',label='z')
plt.legend()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Keyword')

plt.show()

效果图

其实plot能做出许多美轮美奂的图片,这就取决于你的想象力了。

关键词参数列表

关键词参数 描述
color or c 设置线条颜色; accepts any Matplotlib color format.
linestyle 设置线条类型; accepts the line styles seen previously.
linewidth 设置线条宽度; accepts a float value in points.
marker Sets the line marker style.
markeredgecolor 设置标记边缘颜色; accepts any Matplotlib color format.
markeredgewidth 设置标记边缘宽度; accepts float value in points.
markerfacecolor 设置标记内部颜色; accepts any Matplotlib color format.
markersize 设置标记点大小; accepts float values.

设置x轴与y轴的tick标记

源码

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
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

len = 5

x = []
y = []
z = []
m = []

xx = range(len)
for i in range(len):
x.append(np.random.rand())
y.append(np.random.rand())
z.append(np.random.rand())

plt.plot(xx,x,color='blue',linestyle='dashdot',linewidth=2,marker='o',
markerfacecolor='red',markeredgecolor='black',label='x')
plt.plot(xx,y,color='green',linestyle='solid',linewidth=3,marker='s',
markerfacecolor='blue',markeredgecolor='red',label='y')
plt.plot(xx,z,color='cyan',linestyle=':',linewidth=2,marker='^',
markerfacecolor='green',markeredgecolor='blue',label='z')
plt.legend()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Keyword')

plt.xticks(range(len),['a','b','c','d','e'])
plt.yticks(np.arange(0,1,0.05))

plt.show()

效果图

绘图类型

前面说的都是线类型,其实matplotlib可以绘制很多类型,如下图所示。

直方图

直方图 主要用于显示出现的频率值,将某一部分数据集放在一个category里面,这个category称谓
bins 。默认的bins值为10,可以通过参数bins来修改该值,比如下面的源码将其更改为25。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

len = 1000

y = np.random.randn(len)

plt.hist(y,bins=25,color='red',label='Data')
plt.legend()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Histogram Charts')

plt.show()

效果图

误差条形图

对于实验值,精确的值通常情况下是不存在的,因为有各种各样的误差值,那么此时误差条形图就来了。

且看如何使用该图。

源码

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
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,10,0.2)
y = np.exp(-x)
e1 = 0.1 * np.abs(np.random.randn(len(y)))
e2 = 0.15 * np.abs(np.random.randn(len(y)))

plt.errorbar(x,y,xerr=e1,yerr=e2,ecolor='red',fmt='-',label='error')

plt.axis([0,10,-0.5,1.2])

plt.legend()

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Random Value')
plt.title('Error Bar Charts')

plt.show()

效果图

可以看到上面的误差图是对称的,如果是非对称的,只需要将plot的语句更改为如下所示

1
plt.errorbar(x,y,yerr=[e1,e2],ecolor='red',fmt='-',label='error')

非对称效果图

直方图

直方图主要用于可视化两组或者多组值。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt

plt.bar([1,2,3,4],[4,6,3,8])

plt.grid(True)
plt.xlabel('Points')
plt.ylabel('Value')
plt.title('Bar Charts')

plt.show()

参数

  • width:bar的宽度
  • color:bar的颜色
  • xerr,yerr:bar的误差
  • bottom:bar的底部坐标

效果图

更清晰的直方图

源码

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
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

dict = {'A':40,'B':70,'C':35,'D':86}

for i,key in enumerate(dict):
print i,key
plt.bar(i,dict[key])

# 因为宽度默认为0.8,此处的0.4即为每个bar的中间位置
plt.xticks(np.arange(len(dict))+0.4,dict.keys())
# 只显示有用的值
plt.yticks(dict.values())
plt.xlabel('Points')
plt.ylabel('Value')
plt.title('Clear Bar Charts')

plt.show()

效果图

复杂直方图

源码

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
32
33
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

data1 = 10*np.random.rand(5)
data2 = 10*np.random.rand(5)
data3 = 10*np.random.rand(5)

e2 = 0.5 * np.abs(np.random.randn(len(data2)))

locs = np.arange(1,len(data1)+1)

width = 0.27

plt.bar(locs,data1,width=width)

plt.bar(locs+width,data2,yerr=e2,width=width,color='red')

plt.bar(locs+2*width,data3,width=width,color='green')

plt.xticks(locs + width *1.5,locs)

plt.xlabel('Points')
plt.ylabel('Value')
plt.title('Complex Bar Charts')

plt.show()

效果图

饼状图

饼状图主要用于表述某一部分在整体中占得比例。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt

x = [25,35,45]

labels = ['Good','Failed','Passed']

plt.pie(x,labels=labels)

plt.title('Pie Charts')

plt.show()

效果图

参数

  • explode : 所属的部分是否相对于半径有偏移,也就是突出显示的意思
  • colors : 颜色控制
  • labels : 标记
  • shadow : 是否有阴影渲染

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt

x = [5,25,35,45,10]

labels = ['Excellent','Good','Failed','Passed','Bad']

explode = [0.1,0.2,0.0,0.1,0.0]

shadow = [0.0,0.1,0.2,0.1,0.0]

plt.pie(x,labels=labels,explode=explode,shadow=shadow)

plt.title('Pie Charts')

plt.show()

效果图

散点图

散点图主要用于鉴定两组变量的潜在关系,也就是相关关系。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

x = np.random.randn(1000)
y = np.random.randn(1000)

plt.scatter(x,y)

plt.title('Scatter Plot')

plt.show()

效果图

修饰散点图

可以使用下面的几个参数来修饰散点图:

  • s:表示点的大小size
  • c:表示点的颜色color
  • marker:表示点的样式,可以参考前面关于Marker的描述
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

x = np.random.randn(1000)
y = np.random.randn(1000)

size = 50*np.random.randn(1000)
colors = np.random.rand(1000)

plt.scatter(x,y,s=size,c=colors)

plt.title('Scatter Plot')

plt.show()

效果图

极坐标图

极坐标使用了一个完全不同的坐标系,前面的绘图,我们使用的都是笛卡尔坐标系,分别为x与y轴。
而极坐标使用的是半径与角度(或弧度,Matplotlib默认使用角度)。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

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()

效果图

可以通过参数rgridsthetagrid来控制相关的参数显示,比如下面的代码将绘制一个蝴蝶。

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).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

theta = np.arange(0.,2.,1./180.)*np.pi
r = np.abs(np.sin(5*theta)-2.*np.cos(theta))

plt.polar(theta,r)

plt.thetagrids(range(45,360,90))
plt.rgrids(np.arange(0.2,3.,.7),angle=90)

plt.title('Polar Plot')

plt.show()

效果图

说明

转载请注明作者及其出处

github
Homepage
Homepage
CSDN

图片中的文字、注释与箭头

前面的图片我们很简单地添加了x、y轴和标题的问题。
这里我们学着添加图片内部的文字。

其中text中的x、y为坐标值;
figtext为相对坐标,(0,0)为左下角,(1,1)为左上角;

除了text,用的比较多的应该是annotate,既可以写上文字,也可以标记出来具体的点。

annotate的参数:

  • width: The width of the arrow in points
  • frac: The fraction of the arrow length occupied by the head
  • headwidth: The width of the base of the arrow head in points
  • shrink: Moves the tip and the base of the arrow some percent away from
    the annotated point and text, in percentage (so 0.05 is equal to 5%)

annotate已经很好用了,不过我们还可以通过arrow来任意指定箭头的位置、大小和方向。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

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

plt.title('Text && Annotation')

plt.show()

Another

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt

plt.axis([0,10,0,20])

arrstyles = ['-','->','-[','<-','<->','fancy','simple','wedge']

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()

这里需要特别注意的是 ipython -pylab 与from pylab import * 是不一样的。

OO

最后来一个面向对象的,代码如下所示:

1
2
3
4
5
6
7
8
9
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的时候更是如此。

Matplotlib的几个对象

对象 描述
FigureCanvas Figure实例的容器类
Figure Axes实例的容器
Axes 基本绘画单元诸如线、文字等的矩形区域

Subplots

前面的OO模式的代码,来看看几个概念的解释:

  • fig = plt.figure():figure函数返回一个Figure对象,我们可以在其上增加Axes实例
  • ax = fig.add_subplot(121):add_subplot返回一个Axes实例,我们可以在其上绘制图形

add_subplot的使用有三个参数:

1
fig.add_subplot(numrow,numcols,fignum)

比如下面的代码:

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
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

x = np.arange(0,10,0.1)
y = np.random.randn(len(x))
ax1 = fig.add_subplot(121)
#l, = plt.plot(x,y)
#l.set_color('red')
ax1.plot(x,y,'rs-')
ax1.set_title('Random Numbers 1')
ax1.set_xlabel('x')
ax1.set_ylabel('y')

x = np.arange(0,10,0.1)
y = np.random.randn(len(x))
ax2 = fig.add_subplot(122)
ax2.plot(x,y)
ax2.set_title('Random Numbers 2')

plt.show()

多个Figure

Matplotlib 不仅提供了在一个Figure里面绘制多个Axes的功能,还能绘制多幅Figure。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot([1, 2, 3], [1, 2, 3]);
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot([1, 2, 3], [3, 2, 1]);
plt.show()

两个坐标轴

有的时候希望在同一副图像上绘制两个数据集。
特别是对同一个X变量,具有不同的Y值。

这里的技巧在于twinx函数,它会创建第二套坐标,并且与第一套坐标重合,来绘制图形。
不过要注意的是,因为使用了twinx,所有的设置都会重置,包括线条的颜色也会是蓝色,所以为了区分,需要设置颜色。

源码

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
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.1,np.e,0.01)
y1 = np.exp(-x)
y2 = np.log(x)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x,y1)
ax1.set_ylabel('Y values for exp(-x)')

ax2 = ax1.twinx()
ax2.plot(x,y2,'r')
ax2.set_xlim([0,np.e])
ax2.set_ylabel('Y values for ln(x)')
ax2.set_xlabel('Same X for both exp(-x) and ln(x)')

plt.show()

效果图

对数坐标轴

对数坐标轴主要针对有对数关系或者数据增长或缩减比较迅速的数据。

其中semilogx/semilogy一样是将plot与set_xscale/set_yscale合并为一个命令。

而loglog是将x/y全部设置为对数坐标。

源码

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
32
33
34
35
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.,20,0.01)

fig = plt.figure()

ax1 = fig.add_subplot(311)
y1 = np.exp(-x)
ax1.plot(x,y1)
ax1.grid(True)
ax1.set_yscale('log')
ax1.set_ylabel('log y')

ax2 = fig.add_subplot(312)
y2 = np.cos(np.pi*x)
ax2.semilogx(x,y2)
ax2.set_xlim([0,20])
ax2.grid(True)
ax2.set_ylabel('Log X')

ax3 = fig.add_subplot(313)
y3 = np.exp(x/4.)
ax3.loglog(x,y3,basex=3)
ax3.grid(True)
ax3.set_ylabel('Log x and y')

plt.show()

效果图

共享坐标轴

有些情况下,我们希望不同的Figure共享同一个坐标轴,这样在一个坐标改变时会联动其他坐标同时改变。

这对于金融数据、硬件测试、健康状态监测都是很有帮助的。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(20)

fig = plt.figure()

ax1 = fig.add_subplot(311)
ax1.plot(x,x)

ax2 = fig.add_subplot(312,sharex=ax1)
ax2.plot(x*2,x*2)

ax3 = fig.add_subplot(313,sharex=ax1)
ax3.plot(x*3,x*3)

plt.show()

效果图

绘制日期

使用plot_date绘制坐标轴为日期的图形。
下面的linestyle会将各个随机点连接起来,下图有个缺点就是x的日期坐标轴会覆盖。

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt

dates = [dt.datetime.today() + dt.timedelta(days=i) for i in range(10)]

values = np.random.rand(len(dates))

plt.plot_date(mpl.dates.date2num(dates),values,linestyle='-')

plt.show()

效果图

日期格式化

date的格式如下所示:

1
datetime.datetime(2008, 7, 18, 14, 36, 53, 494013)

为了能让Matplotlib使用日期,我们需要将其更改为浮点类型。

可以参考下面的函数:

  • date2num
  • num2date
  • drange

drange比较有用的情况:

1
2
3
4
5
6
7
import matplotlib as mpl
from matplotlib import dates
import datetime as dt
date1 = dt.datetime(2008, 9, 23)
date2 = dt.datetime(2009, 4, 12)
delta = dt.timedelta(days=10)
dates = mpl.dates.drange(date1, date2, delta)

前面绘制的图片比较丑,是真丑,x轴坐标完全看不到。

此时我们就需要使用locator和formatter来格式化坐标轴。其中:

  • locator : control the tick’s position
  • formatter : control the formatting of labels

因为matplotlib有默认的设置,所以最好将这些设置放在plot_date函数的后面,
以防被其重置为原来的值。

解释:

  • fig.autofmt_xdate() 用于美化调整日期显示格式,会旋转以防文字重叠
  • subplots_adjust() 用于调整plot的空间,可以使用bottom,top,left和right关键词以及wspace和hspace关键词

源码

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt

fig = plt.figure()

ax2 = fig.add_subplot(212)
date2_1 = dt.datetime(2008,9,23)
date2_2 = dt.datetime(2008,10,3)
delta2 = dt.timedelta(days=1)
dates2 = mpl.dates.drange(date2_1,date2_2,delta2)
y2 = np.random.rand(len(dates2))
ax2.plot_date(dates2,y2,linestyle='-')
dateFmt = mpl.dates.DateFormatter('%Y-%m-%d')
ax2.xaxis.set_major_formatter(dateFmt)
daysLoc = mpl.dates.DayLocator()
hoursLoc = mpl.dates.HourLocator(interval = 6)
ax2.xaxis.set_major_locator(daysLoc)
ax2.xaxis.set_minor_locator(hoursLoc)
fig.autofmt_xdate()

fig.subplots_adjust(left=0.18)
ax1 = fig.add_subplot(211)
date1_1 = dt.datetime(2008,9,23)
date1_2 = dt.datetime(2009,2,16)
delta1 = dt.timedelta(days=10)
dates1 = mpl.dates.drange(date1_1,date1_2,delta1)
y1 = np.random.rand(len(dates1))
ax1.plot_date(dates1,y1,linestyle='-')
monthsLoc = mpl.dates.MonthLocator()
weeksLoc = mpl.dates.WeekdayLocator()
ax1.xaxis.set_major_locator(monthsLoc)
ax1.xaxis.set_minor_locator(weeksLoc)
monthsFmt = mpl.dates.DateFormatter('%b')
ax1.xaxis.set_major_formatter(monthsFmt)

plt.show()

效果图

Qt4中潜入Matplotlib

Qt应该是跨平台做的算是很好的了,一次编辑,多次编译跨平台。

这一章会介绍:

  • 把Matplotlib的Figure对象嵌入到Qt的组件中
  • 把Matplotlib的Figure和导航工具栏嵌入到Qt的组件中
  • 使用时间来实时更新Matplotlib
  • 使用Qt Designer来绘制GUI,然后调用程序使用Matplotlib

Qt4和PyQt4的简介

Qt是一个跨平台的开发框架,被广泛用于GUI的开发,最有名的应当是KDE桌面环境了。

其实Qt不仅仅是一个GUI开发工具包,它还包含一系列的网络、线程、Unicode、正则表达式、数据库、OpenGL和XML等库。

Qt是跨平台的,可以用与Unix/Linux,Windows,MacOSX。

尽管Qt是用C++来编写的,也可以通过绑定来使用其他语言,诸如Ruby,Java,Perl和Python。

PyQt绑定Qt2和Qt3,PyQt4绑定的是Qt4。

几个比较重要的Qt模块:

  • QtCore:非GUI类
  • QtGui:GLI类
  • QtOpenGL,QtSql,QtSvg,QtText,QtXml,QtNetwork等

嵌入一个Matplotlib Figure到一个Qt窗口

几个需要注意的事情:

  • from matplotlib.figure import Figure :这里的Figure是我们绘图的后端独立单元
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas :这里的FigureCanvas使我们绘图的画布,并且除了是一个Matplotlib类外,还是一个QWidget类,所以可以直接继承使用。

源码

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
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

import sys
from PyQt4 import QtGui
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class Qt4MplCanvas(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)

qApp = QtGui.QApplication(sys.argv)
mpl = Qt4MplCanvas()
mpl.show()
sys.exit(qApp.exec_())

效果图

PyQt4中嵌入Figure和导航条

源码

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
# coding=utf-8

# Author : Guo Shaoguang
# Email : sgguo@shao.ac.cn
# Institute : Shanghai Astronomical Observatory

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

class Qt4MplCanvas(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)

self.setParent(parent)

FigureCanvas.setSizePolicy(self,QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)

class ApplicationWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setWindowTitle("Matplotlib Figure in a Qt4 Window With NavigationToolbar")
self.main_widget = QtGui.QWidget(self)
vbl = QtGui.QVBoxLayout(self.main_widget)
qmc = Qt4MplCanvas(self.main_widget)
ntb = NavigationToolbar(qmc,self.main_widget)

vbl.addWidget(qmc)
vbl.addWidget(ntb)

self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)


qApp = QtGui.QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())

效果图


直方图

源码

效果图

处无为之事,行不言之教;作而弗始,生而弗有,为而弗恃,功成不居!

欢迎关注我的其它发布渠道