1 | import matplotlib.pyplot as plt |
第1句,这是导入Matplotlib接口的主要子模块pyplot绘图的首选格式。这是最好的做法,也是为了避免对全局名称空间的污染,强烈鼓励永远不要像这样导入接口:
1 | from <module> import * |
第2句,此代码行是实际的绘图命令。我们只指定了一个值列表,这些值表示要绘制的点的垂直坐标。matplotlib将使用一个隐式的水平值列表,从0(前值)到n-1(n为列表中的条目数),纵轴表示Y轴,横坐标表示X轴。
第3句,这条命令实际上是打开包含绘图图像的窗口。
1 | x = range(6) |
1.多线图
如果需要在一个图中画出多条线,我们只需要在show之前多次plot就可以了。Matplotlib会给每条线自动选择不同颜色。
1 | x = range(1, 5) |
也可以写成下列形式:
1 | plt.plot(x, [xi*1.5 for xi in x], x, [xi*3.0 for xi in x], x,[xi/3.0 for xi in x]) |
或者
1 | plt.plot(x, x*1.5, x, x*3.0, x, x/3.0) |
2、网格
1 | plt.grid(True) |
3、坐标轴
你可能已经注意到,matplotlib为了精确地包含绘制的数据集自动设置图的界限。有时我们想自己设置坐标轴的界限。我们可以这样:
1 | import matplotlib.py |
如果axis()函数没有参数,它的返回值是实际的界限,有两种方式给这个函数传,一是通过四个值得列表[xmin, xmax, ymin, ymax] ,二是键值对的方式。
我们也可以只限制某个轴的最大值或者最小值
1 | plt.axis(xmin=NNN, ymax=NNN) |
或者通过xlim()和ylim()函数只限制某一个坐标轴的界限。
4、给坐标增加一个标签
1 | import matplotlib.pyplot as plt |
5、增加一个标题
1 | plt.title('Simple plot') |
6、增加图例
1 | plt.plot(x, x*1.5, label='Normal') |
7、保存图到文件
1 | plt.savefig('plot123.png') |
8、Plot()支持可选的第三个参数
1 | plt.plot(X, Y, '<format>', ...) |
plot方法的关键字参数color(或c)用来设置线的颜色。
控制颜色
1 | plt.plot(y, 'y') |
1)颜色的缩写
| Color abbreviation | Color Name |
|---|---|
| b | blue |
| c | cyan |
| g | green |
| k | black |
| m | magenta |
| r | red |
| w | white |
| y | yellow 2 |
2)十六进制字符 #FF00FF
3)(r, g, b) 或 (r, g, b, a),其中 r g b a 取均为[0, 1]之间
4)[0, 1]之间的浮点数的字符串形式,表示灰度值。0表示黑色,1表示白色
也可写成
1 | plt.plot(x1, y1, fmt1, x2, y2, fmt2, ...) |
9、控制线条样式
1 | plt.plot(y, '--', y+1, '-.', y+2, ':') |
- solid
– dashed
-. dashdot
: dotted
‘’, ‘ ‘, None
10、控制标记样式
| Marker abbreviation | Marker style | |
|---|---|---|
| . | Point marker | |
| , | Pixel marker | |
| o | Circle marker | |
| v | Triangle down marker | |
| ^ | Triangle up marker | |
| < | Triangle left marker | |
| > | Triangle right marker | |
| 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 | |
| \ | Vertical line (vline symbol) marker | |
| _ | Horizontal line (hline symbol) marker |
1 | import matplotlib.pyplot as plt |
传递关键字参数
1 | import matplotlib.pyplot as plt |
如果想画两条一样颜色的线,可以这样:
1 | plt.plot(x1, y1, x2, y2, color='green') |
11、X轴和Y轴的刻度
1 | locs, labels = plt.xticks() |
不加任何参数的画,tick函数返回当前位置和标签,
1 | print(plt.xticks()) |
1 | import matplotlib.pyplot as plt |
使用字符来代表x的刻度
12、中文字体不显示的问题
1 | from pylab import mpl |
参考:Matplotlib for python development
python中matplotlib的颜色及线条控制:http://blog.csdn.net/qq_26376175/article/details/67637151