原文地址:https://github.com/lijin-THU/notes-python/blob/master/03-numpy/03.02-matplotlib-basics.ipynb
在使用Numpy之前,需要了解一些画图的基础。
Matplotlib是一个类似Matlab的工具包,主页地址为
导入 matplotlib
和 numpy
:
%pylab
只给定 y
值,默认以下标为 x
轴:
给定 x
和 y
值:
plot(x, sin(x))
多条数据线:
使用字符串,给定线条参数:
plot(x, sin(x), 'r-^')
多线条:
更多参数设置,请查阅帮助。事实上,字符串使用的格式与Matlab相同。
假设我们想画二维散点图:
plot(x, sin(x), 'bo')
可以使用 scatter
达到同样的效果:
scatter(x, sin(x))
事实上,scatter函数与Matlab的用法相同,还可以指定它的大小,颜色等参数:
使用figure()命令产生新的图像:
或者使用 subplot
在一幅图中画多幅子图:
subplot(row, column, index)
默认多次 plot
会叠加:
可以跟Matlab类似用 hold(False)关掉,这样新图会将原图覆盖:
可以在 plot
中加入 label
,使用 legend
加上图例:
或者直接在 legend
中加入:
可以设置坐标轴的标签和标题:
用 'grid()' 来显示网格:
清除已有的图像使用:
关闭当前图像:
关闭所有图像:
close('all')
灰度图片可以看成二维数组:
我们可以用 imshow()
来显示图片数据:
更多参数和用法可以参阅帮助。
这里 cm
表示 colormap
,可以看它的种类:
dir(cm)
使用不同的 colormap
会有不同的显示效果。
imshow(img, cmap=cm.RdGy_r)
在脚本中使用 plot
时,通常图像是不会直接显示的,需要增加 show()
选项,只有在遇到 show()
命令之后,图像才会显示。
从高斯分布随机生成1000个点得到的直方图:
hist(randn(1000))
更多例子请参考下列网站: