Matplotlib 基础
在使用Numpy之前,需要了解一些画图的基础。
Matplotlib是一个类似Matlab的工具包,主页地址为
http://matplotlib.org
导入 matplotlib 和 numpy:
import matplotlib.pyplot as plt
from numpy import *
plot 二维图
plt.plot(y)
plt.plot(x, y)
plt.plot(x, y, format_string)
只给定 y 值,默认以下标为 x 轴:
x = linspace(0, 2 * pi, 50)
plt.plot(sin(x))
给定 x 和 y 值:
plt.plot(x, sin(x))
多条数据线:
plt.plot(x, sin(x),
x, sin(2 * x))
使用字符串,给定线条参数:
plt.plot(x, sin(x), 'r-^')
多线条:
plt.plot(x, sin(x), 'b-o',
x, sin(2 * x), 'r-^')
更多参数设置,请查阅帮助。事实上,字符串使用的格式与Matlab相同。
scatter 散点图
scatter(x, y)
scatter(x, y, size)
scatter(x, y, size, color)
假设我们想画二维散点图:
plt.plot(x, sin(x), 'bo')
可以使用 scatter 达到同样的效果:
plt.scatter(x, sin(x))
事实上,scatter函数与Matlab的用法相同,还可以指定它的大小,颜色等参数:
x = np.random.rand(200)
y = np.random.rand(200)
size = np.random.rand(200) * 30
color = np.random.rand(200)
plt.scatter(x, y, size, color)
# 显示颜色条
plt.colorbar()
多图
使用figure()命令产生新的图像:
t = linspace(0, 2*pi, 50)
x = sin(t)
y = cos(t)
plt.figure()
plt.plot(x)
plt.figure()
plt.plot(y)
或者使用 subplot 在一幅图中画多幅子图:
subplot(row, column, index)
plt.subplot(1, 2, 1)
plt.plot(x)
plt.subplot(1, 2, 2)
plt.plot(y)
向图中添加数据
默认多次 plot 会叠加:
plt.plot(x)
plt.plot(y)
标签
可以在 plot 中加入 label ,使用 legend 加上图例:
plt.plot(x, label='sin')
plt.plot(y, label='cos')
plt.legend()
或者直接在 legend中加入:
plt.plot(x)
plt.plot(y)
plt.legend(['sin', 'cos'])
坐标轴,标题,网格
可以设置坐标轴的标签和标题:
plt.plot(x, sin(x))
plt.xlabel('radians')
# 可以设置字体大小
plt.ylabel('amplitude', fontsize='large')
plt.title('Sin(x)')
用 ‘grid()’ 来显示网格:
plt.plot(x, sin(x))
plt.xlabel('radians')
plt.ylabel('amplitude', fontsize='large')
plt.title('Sin(x)')
plt.grid()
清除、关闭图像
清除已有的图像使用:
clf()
关闭当前图像:
close()
关闭所有图像:
close('all')
imshow 显示图片
灰度图片可以看成二维数组:
# 导入lena图片
from scipy.misc import ascent
img = ascent()
img
我们可以用 imshow() 来显示图片数据:
plt.imshow(img,
# 设置坐标范围
extent = [-25, 25, -25, 25])
plt.colorbar()
更多参数和用法可以参阅帮助。
从脚本中运行
在脚本中使用 plot 时,通常图像是不会直接显示的,需要增加 show() 选项,只有在遇到 show() 命令之后,图像才会显示。
直方图
从高斯分布随机生成1000个点得到的直方图:
plt.hist(np.random.randn(1000))
更多例子请参考下列网站:
http://matplotlib.org/gallery.html

















