matplotlib.pyplot(as mp or as plt)提供基于python语言的绘图函数
引用方式: import matplotlib.pyplot as mp / as plt 本章内容拟按官方手册(NumPy Reference, Release 1.14.5 )中的 plt 形式
像matlab一样,matplotlib.pyplot是一些命令样式函数。
pyplot函数都可以创建图形、再图形中创建绘图区、再绘图区中画线、用标签装饰图形等操作。
在pyplot的函数调用中,隐藏了各种状态,这就意味着要始终跟踪到当前的图形和绘图区域,并且绘图函数要指向当前的坐标轴(注意这里的坐标轴是数字坐标轴,而不是严格意义的数学术语)。
1 plot
plot()函数是用来绘制二维图像的,
plot的广泛的定义为:
plot(*args, **kwargs)
此定义意味着plot()这一通用函数可以接受任意参数
args 和 kwargs 参数具体化
1.1 asgs参数
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
x - 值是可选的,
y - 值是必选的,也就是说,当一个值时,默认为y
fmt - 用于定义基本格式化如颜色、标记和直线样式的shortcut string
注:可以增加多个Y值,及其相关基本格式化shortcut string
示例1
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show() # 不写此语句,则图像存在于内存中,不会输出到显示器上
示例2 没有x轴时
import matplotlib.pyplot as plt
# x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(y)
plt.show()
当仅给plot()的args参数提供一个列表/数组时,则默认为y,此时缺省x;x轴上的数值是自动生成的,x轴上的值是默认从0开始,且x上的长度值与y轴一致,所以此时x轴上的值为[0, 1, 2, 3]
示例3
import matplotlib.pyplot as plt
#args参数 ‘bo’ 格式化了图形形式
plt.plot([1, 2, 3, 4], [1, 4, 9, 16],'bo')
plt.show()
在plot()函数中,默认为绿色实线,对应格式字符串为‘b-’;实际上,标示线条颜色和类型的格式串来自于matlab。
另外还有一些其他格式字符串来控制线条样式或标记
字符 描述
'-' 实线
'--' 虚线
'-.' 点与线
':' 点
'.' 点标记
',' 像素标记
'o' 圆圈标记
'v' 倒三角标记
'^' 正三角标记
'<' 左三角标记
'>' 右三角标记
'1' 向下Y标记
'2' 向上Y标记
'3' 向左Y标记
'4' 向右Y标记
's' 正方形标记
'p' 五角星标记
'*' *标记
'h' 六边形1 标记
'H' 六边形2 标记
'+' +标记
'x' x标记
'D' 钻石标记
'd' 薄砖石标记
'|' 垂直线标记
'_' 水平线标记
在默认格式字符串中,‘b-’ 中的 ‘-’ 表示实线,前面的字母 ‘b’ 则表示颜色
颜色相关的格式字符串及描述
字符 描述
‘b’ blue(蓝色)
‘g’ green(绿色)
‘r’ red(红色)
‘c’ cyan(青色)
‘m’ magenta(品红)
‘y’ yellow(黄色)
‘k’ black(黑色)
‘w’ white(白色)
除了常见的颜色缩写外,还有RGB / RGBA颜色元组((0,1,0,1)),或者灰度强度作为字符串( ‘ 0.8 ’ ),或者十六进制字符串(‘#0080000’)
如果不使用上述简写格式字符,也可以采用kwargs字典参数形式进行控制
1.2 kwargs参数
在一定程度上,kwargs参数与args参数是等效的。如下示例所示
示例1
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x,y,'go--',linewidth = 2, markersize = 12)
# plt.plot(x, y, color='green', marker='o', linestyle='dashed',linewidth=2, markersize=12)
plt.show()
在示例中,采用 args 和 kwargs 的打印效果是一样的
在控制线条属性中,可以使用关键字参数进行设置
plt.plot(x, y, linewidth=2.0)
使用Line2D对象的setter方法,plot函数返回Line2D对象列表,例如 line1, line2 = plot(x1, y1, x2, y2) ,
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [1, 4, 9, 16] L1,L2 = plt.plot(x,y,y,x,linewidth = 3) print(L1) # Line2D(_line0) print(type(L1)) # <class 'matplotlib.lines.Line2D'> print(L2) # Line2D(_line1) plt.show()
在下段代码中,假设只有一行,因此返回的列表长度为1,使用元组来拆开line,并获取到列表的第一个元素。
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [1, 4, 9, 16] line, = plt.plot(x,y,'-') # 记得添加逗号, # 否则会报错AttributeError: # 'list' object has no attribute 'set_antialiased' # 也就意味plot返回的是数组list, # 使用setter方法,则返回的是Line2D对象 line.set_antialiased(False) # turn off antialising plt.show()
使用 setp() 命令,实现一行设置多个属性,采用一个或一组对象可以使 setp 工作更加 transparently(明亮地,显然地,易觉察地)
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y = [1, 4, 9, 16] lines = plt.plot(x, y, x, y) # use keyword args plt.setp(lines, color='r', linewidth=2.0) plt.show()
采用 MATLAB 形式的键值对也可,此处略。
1.3 Line2D属性
在xdata、ydata序列中创建带有x、y数据的Line2D实例。
详细参数见 matplotlib.lines.Line2D,里面有针对每一个参数的详细讲解
Property | Description |
---|---|
agg_filter | a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array |
alpha | float (0.0 transparent through 1.0 opaque) |
animated | bool |
antialiased or aa | bool |
clip_box | a Bbox instance |
clip_on | bool |
clip_path | [(Path , Transform ) | Patch | None] |
color or c | any matplotlib color |
contains | a callable function |
dash_capstyle | [‘butt’ | ‘round’ | ‘projecting’] |
dash_joinstyle | [‘miter’ | ‘round’ | ‘bevel’] |
dashes | sequence of on/off ink in points |
drawstyle | [‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’] |
figure | a Figure instance |
fillstyle | [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’] |
gid | an id string |
label | object |
linestyle or ls | [‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ | (offset, on-off-dash-seq) | '-' | '--' | '-.' | ':' | 'None' | ' ' | '' ] |
linewidth or lw | float value in points |
marker | A valid marker style |
markeredgecolor or mec | any matplotlib color |
markeredgewidth or mew | float value in points |
markerfacecolor or mfc | any matplotlib color |
markerfacecoloralt or mfcalt | any matplotlib color |
markersize or ms | float |
markevery | [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float] |
path_effects | AbstractPathEffect |
picker | float distance in points or callable pick function fn(artist, event) |
pickradius | float distance in points |
rasterized | bool or None |
sketch_params | (scale: float, length: float, randomness: float) |
snap | bool or None |
solid_capstyle | [‘butt’ | ‘round’ | ‘projecting’] |
solid_joinstyle | [‘miter’ | ‘round’ | ‘bevel’] |
transform | a matplotlib.transforms.Transform instance |
url | a url string |
visible | bool |
xdata | 1D array |
ydata | 1D array |
zorder | float |
2 多图和多坐标轴
matlab、pyplot都有当前图和当前坐标轴的概念,所有的绘图命令都应用于当前轴。
函数gca()返回当前轴,get current axes
函数gcf()返回当前图,get current figure
1 import numpy as np 2 import matplotlib.pyplot as plt 3 4 def f(t): 5 return np.exp(-t) * np.cos(2*np.pi*t) 6 7 t1 = np.arange(0.0, 5.0, 0.1) 8 t2 = np.arange(0.0, 5.0, 0.02) 9 10 plt.figure(1) 11 plt.subplot(211) 12 plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') 13 14 plt.subplot(212) 15 plt.plot(t2, np.cos(2*np.pi*t2), 'r--') 16 plt.show()

10行 figure()命令是可选的,
这儿的figure()
命令是可选的,因为figure(1)
会被默认执行,就像subplot(111)
也会被默认执行,只要你不手动定义任何的坐标轴。subplot()
命令指定行数(numrows)、列数(numcols)、图形号(fignum),图形号的范围是从1到numrows*numcols
。如果numrows*numcols<10
,subplot()
参数里的逗号是可选的。所以subplot(211)
等同于subplot(2, 1, 1)
。你可以创建任意数量的子图和坐标轴。如果你想手动放置坐标轴,例如不在一个直角网格里,可以使用axes()
命令,axes可以让你给坐标轴定义位置,像axes([left, bottom, width, height])
,参数都是小数(0-1)坐标。两个例子: