matplotlib是python里用于绘图的专用包,功能十分强大。下面介绍一些最基本的用法:

一、最基本的划线

先来一个简单的示例,代码如下,已经加了注释:

import matplotlib.pyplot as plt
import numpy as np

# 先获取一个图表
plt.figure()

# 设置图表的标题
plt.title("sale report")

# 设置y轴的label标签
plt.ylabel("amount")

# 设置x轴的label标签
plt.xlabel("month")

# 模拟一些(X,Y)坐标数据(注:习惯上用大写表示矩阵)
X = np.arange(0, 13)
Y = np.array([100, 200, 200, 300, 400, 600, 500, 550, 600, 700, 800, 750, 800])

# 将x轴的刻度范围限制为-0.5~12.2
plt.xlim(-0.5, 12.2)

# 将y轴的刻度范围限制为0~1000
plt.ylim(0, 1000)

# 将(X,Y)坐标用red红色画线
plt.plot(X, Y, 'r')

# X坐标也可以省略,只要Y轴的坐标值即可,--表示是虚线
plt.plot(Y + 50, '--')

# g+表示green绿色,画图的样式为+号
plt.plot(Y - 50, 'g+')

# 同时划二条线,第1个是yellow黄色,第2个是magenta色,另外还设置了样式1
plt.plot(Y - 100, 'y', Y - 150, 'm1')

# 渲染出来
plt.show()

Matplotlib新手上路(上)

注:plt中有很多缩写,比如r代表red,y代表yellow,xlim即x-axis-limit(x轴的限制),另外g+,表示颜色是green,而后面的+号表示划线的样式。从源码中可以找到更多的缩写说明。 matplotlib/axes/_axes.py 在这个文件中,plot方法的注释里有相关描述:

 1 The following format string characters are accepted to control
 2 the line style or marker:
 3 
 4 ================    ===============================
 5 character           description
 6 ================    ===============================
 7 ``'-'``             solid line style
 8 ``'--'``            dashed line style
 9 ``'-.'``            dash-dot line style
10 ``':'``             dotted line style
11 ``'.'``             point marker
12 ``','``             pixel marker
13 ``'o'``             circle marker
14 ``'v'``             triangle_down marker
15 ``'^'``             triangle_up marker
16 ``'<'``             triangle_left marker
17 ``'>'``             triangle_right marker
18 ``'1'``             tri_down marker
19 ``'2'``             tri_up marker
20 ``'3'``             tri_left marker
21 ``'4'``             tri_right marker
22 ``'s'``             square marker
23 ``'p'``             pentagon marker
24 ``'*'``             star marker
25 ``'h'``             hexagon1 marker
26 ``'H'``             hexagon2 marker
27 ``'+'``             plus marker
28 ``'x'``             x marker
29 ``'D'``             diamond marker
30 ``'d'``             thin_diamond marker
31 ``'|'``             vline marker
32 ``'_'``             hline marker
33 ================    ===============================
34 
35 
36 The following color abbreviations are supported:
37 
38 ==========  ========
39 character   color
40 ==========  ========
41 'b'         blue
42 'g'         green
43 'r'         red
44 'c'         cyan
45 'm'         magenta
46 'y'         yellow
47 'k'         black
48 'w'         white
49 ==========  ========
View Code

相关文章: