Python学习笔记(7)——Matplotlib中的Axes.plot(绘制点、线和标记)的用法
Axes.plot用于绘制XY坐标系的点、线或其他标记形状。
1.调用方法
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
- 点和线的坐标由参数x,y提供。可选参数fmt是一个快捷字符串,用于定义颜色、标记符合和线条形状,例如:
>>> plot(x, y) # 使用默认颜色和形状
>>> plot(x, y, 'bo') # 使用蓝色(blue)、圆点型绘图
>>> plot(y) # 绘制y坐标,x坐标使用列表0..N-1
>>> plot(y, 'r+') # 同上,但使用红色(red)+号形状
- 也可以使用Line2D属性作为关键字,以此来更好的控制显示效果,Line属性和fmt可以混合使用,下面两种写法效果相同。当关键字与fmt冲突时,关键字优先。
>>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
... linewidth=2, markersize=12)
- 绘制带标签的数据——使用data参数可以很方便的绘制带标签的数据,所有可索引的类型都支持,例如dict、pandas.DataFame或结构化的numpy数组。
>>> plot('xlabel', 'ylabel', data=obj)
- 绘制多组数据——有多种方法可以绘制多组数据,例如:
最直接的方式就是多次调用plot方法。
>>> plot(x1, y1, 'bo')
>>> plot(x2, y2, 'go')
或者,你的数据本身是一个二维数组,就可以直接传入x,y,数据的每一列都会被绘制成图。例如:数组a的第一列代表x值,其他列代表y值。
>>> plot(a[0], a[1:])
第三种方法是用多组 [x], y, [fmt] 指定数据集。这种情况下,任何关键字参数将被用于所有数据集,而且这种语法也不能与参数data同时用。
>>> plot(x1, y1, 'g^', x2, y2, 'g-')
默认情况下,每一条线的样式会设为一组样式集中的不同样式,如果想区别于默认样式就可以使用fmt和线条属性参数。或者也可以使用 'axes.prop_cycle'改变默认样式集。
2. 参数
- x,y:类数组或极坐标。
水平/垂直坐标系中的数据点,x是可选参数,默认为[0,..., N-1]
.
通常,参数x,y是长度为N的数组,也支持极坐标(相当于一个常数值数组)。
参数也可以是二维的,此时,每一列代表一个数据集。
- fmt:字符串,可选参数。
格式化字符串,例如‘ro’代表红色圆圈。
格式字符串是用于快速设置基本线条样式的缩写,这些样式或更多的样式可通过关键字参数来实现。
fmt = '[color][marker][line]'
color(颜色)、marker(标记点)、line(线条)都是可选的,例如如果指定line而不指定marker,将绘制不带标记点的线条。
支持的颜色缩写如下:
字符 | 颜色 |
---|---|
'b' |
blue 蓝色 |
'g' |
green 绿色 |
'r' |
red 红色 |
'c' |
cyan 青色 |
'm' |
magenta 紫红色 |
'y' |
yellow 黄色 |
'k' |
black 黑色 |
'w' |
white 白色 |
支持的marker缩写如下:
字符 | 描述 |
---|---|
'.' |
point marker 点 |
',' |
pixel marker 像素 |
'o' |
circle marker 圆形 |
'v' |
triangle_down marker 下三角 |
'^' |
triangle_up marker 上三角 |
'<' |
triangle_left marker 左三角 |
'>' |
triangle_right marker 右三角 |
'1' |
tri_down marker |
'2' |
tri_up marker |
'3' |
tri_left marker |
'4' |
tri_right marker |
's' |
square marker 方形 |
'p' |
pentagon marker 五角形 |
'*' |
star marker 星型 |
'h' |
hexagon1 marker 六角形1 |
'H' |
hexagon2 marker 六角形2 |
'+' |
plus marker 加号 |
'x' |
x marker ×型 |
'D' |
diamond marker 钻石型 |
'd' |
thin_diamond marker 细钻石型 |
'|' |
vline marker 竖线型 |
'_' |
hline marker 横线型 |
支持的line缩写如下:
字符 | 描述 |
---|---|
'-' |
solid line style 实线 |
'--' |
dashed line style 虚线 |
'-.' |
dash-dot line style 交错点线 |
':' |
dotted line style 点线 |
- data:索引类型的对象,可选。
有标记的数据对象,如果给定该参数,请提供要在x和y中绘制的标签名称。
3. 返回值
- lines:
代表绘制数据的Line2D对象。
4. 其他参数
- scalex, scaley:布尔值,可选,默认为True。
这组参数用于设置图形坐标的边界是否适应数据的边界,参数值传给autoscale_view。
-
**kwargs:
Line2D
属性,可选
kwargs用于设置特殊的属性,如线条标签、线条宽度、平滑效果、标记点的颜色等。
>>> plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
>>> plot([1,2,3], [1,4,9], 'rs', label='line 2')
如果使用一个命令绘制多条线,那么kwargs的样式将被用于所有线条。
Line2D
包含的属性如下:
属性 | 描述 |
---|---|
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 |
animated |
bool |
antialiased |
bool |
clip_box |
Bbox |
clip_on |
bool |
clip_path |
[(Path , Transform ) | Patch | None] |
color |
color |
contains |
callable |
dash_capstyle |
{'butt', 'round', 'projecting'} |
dash_joinstyle |
{'miter', 'round', 'bevel'} |
dashes |
sequence of floats (on/off ink in points) or (None, None) |
drawstyle |
{'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'} |
figure |
Figure |
fillstyle |
{'full', 'left', 'right', 'bottom', 'top', 'none'} |
gid |
str |
in_layout |
bool |
label |
object |
linestyle |
{'-', '--', '-.', ':', '', (offset, on-off-seq), ...} |
linewidth |
float |
marker |
unknown |
markeredgecolor |
color |
markeredgewidth |
float |
markerfacecolor |
color |
markerfacecoloralt |
color |
markersize |
float |
markevery |
unknown |
path_effects |
AbstractPathEffect |
picker |
float or callable[[Artist, Event], Tuple[bool, dict]] |
pickradius |
float |
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 |
matplotlib.transforms.Transform |
url |
str |
visible |
bool |
xdata |
1D array |
ydata |
1D array |
zorder |
float |
5. 一些示例
- 基本绘图
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
fig.savefig("test.png")
plt.show()
- 用一个命令绘制3条不同的线
import numpy as np
import matplotlib.pyplot as plt
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
- 3种不同的连线效果
import numpy as np
import matplotlib.pyplot as plt
def plot_angle(ax, x, y, angle, style):
phi = np.radians(angle)
xx = [x + .5, x, x + .5 * np.cos(phi)]
yy = [y, y, y + .5 * np.sin(phi)]
ax.plot(xx, yy, lw=8, color='blue', solid_joinstyle=style)
ax.plot(xx[1:], yy[1:], lw=1, color='black')
ax.plot(xx[1::-1], yy[1::-1], lw=1, color='black')
ax.plot(xx[1:2], yy[1:2], 'o', color='red', markersize=3)
ax.text(x, y + .2, '%.0f degrees' % angle)
fig, ax = plt.subplots()
ax.set_title('Join style')
for x, style in enumerate((('miter', 'round', 'bevel'))):
ax.text(x, 5, style)
for i in range(5):
plot_angle(ax, x, i, pow(2.0, 3 + i), style)
ax.set_xlim(-.5, 2.75)
ax.set_ylim(-.5, 5.5)
plt.show()
更多示例参考官方文档。
参考:
官方文档https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot