一、类MATLAB API
from pylab import *
%matplotlib qt #使用 qt 作为图形后端
例:
from pylab import *
from numpy import *
x = linspace(0, 5, 10)
y = x ** 2
figure()
plot(x, y, 'r')
xlabel('x')
ylabel('y')
title('title')
show()
创建子图,选择绘图用的颜色与描点符号:
subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');
此类 API 的好处是可以节省代码量,但处理复杂图表时, matplotlib 面向对象 API 是一个更好的选择。
二、matplotlib 面向对象 API
import matplotlib.pyplot as plt
这种方法不创建一个全局实例,而是将新建实例的引用保存在 fig 变量中,如果想在图中新建一个坐标轴实例,只需要调用 fig 实例的 add_axes 方法:
对上上例二次函数的绘制改为:
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
#如果不在意坐标轴在图中的排放位置️,可以使用matplotlib的布局管理器如subplots 则上两句可改为:
# fig, axes = plt.subplots()
axes.plot(x, y, 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title')
fig
这样对于图表的绘制有了完全的控制权,可以很容易地多加一个坐标轴到图中:
fig = plt.figure()
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes
# main figure
axes1.plot(x, y, 'r')
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('title')
# insert
axes2.plot(y, x, 'g')
axes2.set_xlabel('y')
axes2.set_ylabel('x')
axes2.set_title('insert title');
subplots布局管理器用法举例:
fig, axes = plt.subplots(nrows=1, ncols=2)
for ax in axes:
ax.plot(x, y, 'r')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')
fig.tight_layout() #若标签重叠可使用 fig.tight_layout 自动调整标签的位置
fig
图表尺寸,长宽比 与 DPI
在创建 Figure 对象的时候,使用figsize 与 dpi 参数能够设置图表尺寸与DPI, 创建一个800*400像素,每英寸100像素的图如下:
fig = plt.figure(figsize=(8,4), dpi=100)
=><matplotlib.figure.Figure at 0x7f29c2b47990>
用在布局管理器上:
fig, axes = plt.subplots(figsize=(12,3))
保存图表
savefig 用于保存图表:
fig.savefig("filename.png")
fig.savefig("filename.png", dpi=200) #可以有选择地指定DPI,并且选择不同的输出格式
Matplotlib 可以生成多种格式的高质量图像,包括PNG,JPG,EPS,SVG,PGF 和 PDF。如果是科学论文的话尽量使用pdf格式。 (pdflatex 编译的 LaTeX 文档使用 includegraphics 命令就能包含 PDF 文件)。 一些情况下,PGF也是一个很好的选择。
图例,轴标 与 标题
set_title:给坐标轴实例加上标题:
ax.set_title(“title”)
set_xlabel 与 set_ylabel:设置坐标x轴与y轴的标签:
ax.set_xlabel(“x”)
ax.set_ylabel(“y”)
有两种方法在图中加入图例。一种是调用坐标轴对象的 legend 方法,传入与之前定义的几条曲线相对应的图例文字的 列表/元组:
ax.legend([“curve1”, “curve2”, “curve3”])
这种方式容易出错,比如增加了新的曲线或者移除了某条曲线。更好的方式是在调用 plot方法时使用 label=”label text” 参数,再调用 legend 方法加入图例:
ax.plot(x, x**2, label="curve1")
ax.plot(x, x**3, label="curve2")
ax.legend();
legend 还有一个可选参数 loc 决定画出图例的位置,最常用的值如下:
ax.legend(loc=0) # let matplotlib decide the optimal location
ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner
# .. many more options are available
=> <matplotlib.legend.Legend at 0x4c863d0>
标题,轴标,与图例的用法例子:
import matplotlib.pyplot as plt
from numpy import *
x = linspace(0, 5, 10)
fig, ax = plt.subplots()
ax.plot(x, x**2, label=