Matplotlib是Python中最常用的可视化工具之一,可以非常方便地创建海量类型的2D图表和一些基本的3D图表。本文翻译自Jupyter nbviewer中的第四讲,主要介绍了绘制2D图像的相关信息,图像的位置、大小,曲线的样式、宽度,坐标轴的刻度、数值、标签,以及图例、标题参数的设置,还包括各种类型的图像的绘制,如柱状图、色图、等高线图等等。作为延伸,又介绍了3D曲线图、框线图和投影图,以及动图的制作。最后作为了解,介绍了后端以及图片视频格式的相关内容。
作者:J.R. Johansson (邮箱:jrjohansson@gmail.com)
最新版本的用法介绍见网站github.com/jrjohansson/scientific-python-lectures.其他相关介绍见jrjohansson.github.io.

简介
Matplotlib是一个绘制2D和3D科学图像的库,它包含了以下的优点:
容易学习和掌握
兼容LaTeX格式的标题和文档
可以控制图像中的每个元素,包括图像大小和扫描精度。
对于很多格式都可以高质量的输出图像,包括PNG,PDF,SVG,EPS和PGF.
可以生成图形用户界面(GUI),做到交互式的获取图像以及无脑生成图像文件(通常用于批量作业)
Matplotlib最重要的一个特点,也是它作出的图像非常适合作为科学出版物的原因,是因为图像可以完全被程序所控制。这一点对于图像重现非常重要,同时为更新数据后重新作图以及改变图像形状提供了方便。更多关于Matplotlib网页请见http://matplotlib.org/
在Python中调用Matplotlib函数包有两种方法,一种是在pylab模式中包含一个星号(简单的方法)
from pylab import *
另一种是在matplotlib.pyplot模式下使用plt(整洁的方法):
import matplotlib
import matplotlib.pyplot as plt
In [4]: import numpy as np
MATLAB样式的API
学习用matplotlib绘制图像最简单的方法使用matplotlib自身提供的类似MATLAB的API。它和MATLAB绘制图像的函数非常相近,所以熟悉MATLAB的用户可以非常容易的上手。采用在pylab模式中包含星号的方式可以使用matplotlib中的API:
from pylab import *
例:
采用一个类似MATLAB作图的API,能够做出以下简单的图像:
x = np.linspace(0, 5, 10)
y = x **
figure() plot(x, y, 'r') xlabel('x') ylabel('y') title('title') show()

MATLAB中大多数绘图相关的函数都能在pylab模式下实现。例如将多个图像绘制在一个窗口中,以及选择颜色和线条类型:
subplot(1,2,1)
plot(x, y, 'r--')
subplot(1,2,2)
plot(y, x, 'g*-');

pylab这种MATLAB格式的API有一个优点,对于MATLAB熟悉的用户能够非常容易上手,而且对于绘制简单图像而言不需要花费很多精力去学习。
然而,对于并不是特别简单的图像,并不推荐使用MATLAB类似的API,学习使用matplotlib面向对象的绘图API是一种更好更强大的方法。对于多个复杂图像绘制在一个窗口中,插入图像和加入其它成分这样的复杂操作,matplotlib的API能够很好的解决。
matplotlib面向对象的API
面向对象的程序的主要思路是让用户能够面向对象来使用函数和进行操作,而不是像MATLAB类似的API一样采用全局的程序状态。Matplotlib的优势在绘制多个图像或者一个图像窗口中包含多个子图像的时候能够彰显出来。
我们这次采用面向对象的API来绘制和前一个例子相似的图像,但是这次我们存储一个引用在新创建的fig变量的图像中,而并不直接创建一个全局的图像,然后我们创建一个新的坐标轴图像axes(采用Figure函数族中的add_axes方法):


尽管代码看起来多了一点,但是我们现在能够完全掌控图像的坐标轴位置,并且能够在图像上轻易增加多个坐标轴:

如果我们并不关心坐标轴的位置是否要明确处于画图窗口的哪个位置,我们可以采用matplotlib布局工具中的一个,例如subplots,用法如下:


这样的代码很简单,但是如果坐标轴或者标签重合在一起,就显得不太美观了。

我们可以采用fig.tight_layout方法来解决这个问题,它能够更自动调整坐标轴在图像窗口的位置,从而避免重合的发生:


图像大小,纵横比和图像精度
Matplotlib在绘制Figure对象时,允许用户确定图像纵横比、图像精度和大小,采用figsize和dpi关键字参数。figsize是关于图像宽度和高度(单位:英寸)的元组型变量,dpi是每英寸点数(像素)。为创建一个800×400像素,每英寸点数为100的图像,代码如下:
fig = plt.figure(figsize=(8,4), dpi=100)
同样的操作可以在布局工具中运行,例如subplots函数:

保存图像
我们可以采用Figure函数族中的savefig方法来存储图像:
fig.savefig("filename.png")
这里我们还可以确定图像精度,以及选择不同的输出格式:
fig.savefig("filename.png", dpi=200)
可以存储什么样的格式?为获取最高质量图像,我们应该选择哪种格式?
Matplotlib可以产生各种高质量的输出格式,包括PNG,JPG,EPS,SVG,PGF和PDF。在学术论文中,如果可以的话推荐使用PDF格式(LaTeX文件编译pdflatex可以采用includegraphics来编译PDF)。在一些情况下,PGF格式也是一种好的选择。
图例、标签和标题
既然我们已经介绍了绘图和添加坐标轴的基本方法,我们现在来介绍如何添加图例、标签和标题。
标题
标题可以加在每个图像上,可以采用set_title方法来设置标题:
ax.set_title("title");
坐标轴标签
同样的,用set_xlabel和set_ylabel可以设置X和Y轴的标签:
ax.set_xlabel("x")
ax.set_ylabel("y");
图例
图像中曲线的图例可以用两种方式添加,一种是用坐标轴对象的legend指令,对于之前定义的曲线添加列表或元组形式的文本:
In [20]: ax.legend(["curve1", "curve2", "curve3"]);
上面这种方法其实是MATLAB的API,如果图像上的曲线被添加或者删除时可能会报错(导致错误的添加图例)。
一种更好的方法是在绘图或添加其他元素的时候利用label="label text" 关键字参数,然后用无参数的legend指令把图例添加到图像上:
Iax.plot(x, x**2, label="curve1")
ax.plot(x, x**3, label="curve2")
ax.legend();
这种方法的优点是,如果在图像上添加或者删除曲线,图例会随之自动更新。
legend函数有一个可供选择的关键字参数loc,用来确定图例添加的位置,loc参数的允许值是数值型代码,详见http://matplotlib.org/users/legend_guide.html#legend-location.下面列举了一些常见的loc值:

运用上面介绍的关于标题,坐标轴标签和图例的内容,我们可以作出如下图像:


文本格式: LaTeX,字体大小,字体样式
上面的绘制图像的方法都非常实用,但是还不能满足发表论文所需的标准。第一也是最重要的,我们需要采用LaTeX文本格式;第二,我们需要能够调整字体大小以适应出版社所需的要求。
Matplotlib与LaTeX非常兼容,我们只需采用美元符号来封装LaTeX的文本(图例,题目,标签等等),例如:"y=x3y=x3"。
但是这里我们可能在转换LaTeX代码和Python字符串的过程中出现一点问题。在LaTeX中,我们经常用反斜杠符号,例如用\alpha来产生符号α. 但是反斜杠在Python中已经有别的含义(转义码字符)。为了避免Python和LaTeX代码混淆,我们采用“原始”字符串。原始字符串带有前缀“r”,例如r"\alpha" 或者 r'\alpha' 而不是 "\alpha" or '\alpha':


我们也可以改变全局的字体大小和字体样式,使得图像中的所有文本元素都适用(刻度标记、坐标轴标签,标题和图例等等):


全局字体选择STIX字体样式是一个好的选择:


或者,我们可以要求matplotlib在图像中采用LaTeX文本元素:



设置颜色,线条宽度和线条类型
颜色
用matplotlib,我们可以运用各种方法定义线条颜色和其他图像元素。首先,我们可以运用MATLAB的语法,定义'b'代表蓝色,'g'代表绿色,等等。同样,matplotlib也支持用MATLAB的API设置线条类型,例如:'b.-'代表蓝色虚点线:

我们也可以定义用颜色的英文名称定义,或者RGB十六进制码,或者用color和alpha关键字参数来选择性提供α值:


线条和标记样式
我们可以用linewidth或者lw关键字参数来调整线宽度,线条样式则可以在linestyle或者ls关键字参数中选择:



控制坐标轴外观
坐标轴外观是一个图像重要的方面,特别是我们经常需要更改它以满足出版刊物对于图像的要求。我们需要控制刻度和标签的位置,更改字体大小和坐标轴标签。这一节中,我们将会学习如何控制matplotlib图像的这些参数。
绘图范围
首先我们想要设置坐标轴的范围,可以运用坐标轴对象中的set_ylim和set_xlim,或者axis('tight')来自动设置“紧密结合”的坐标范围:


对数标度
对于单个或者两个坐标轴都可以设置对数标度。这个功能其实仅仅是Matplotlib全部变换系统的一个应用。每个坐标标度可以分别用set_xscale和set_yscale来设置(值填入“log”即可):


刻度的放置以及用户定义的刻度标签
我们可以用set_xticks和set_yticks来明确确定坐标轴的刻度位置,二者都需要提供一个列表型数值。对于每个刻度位置,我们可以用set_xticklabels和set_yticklabels来提供一个用户定义的文本标签:


Matplotlib图像还有很多更为高级的方法来控制主刻度和副刻度的位置,比如在不同环境下自动确定其位置,详见http://matplotlib.org/api/ticker_api.html.
科学计数法
对于坐标轴上出现的较大的数字,通常运用科学计数法:


坐标数字以及坐标标签的位置


坐标轴位置调整
不幸的是,当保存图像时候,标签有时会被缩短,因此需要微调坐标轴的位置,这可以由subplots_adjust来实现:


坐标轴网格
用坐标轴对象中的grid可以使用和取消网格线。我们也可以用plot函数中同样的关键字参数来定制网格样式:
In [44]: fig, axes = plt.subplots(1, 2, figsize=(10,3)) # 默认网格外观 axes[0].plot(x, x**2, x, x**3, lw=2) axes[0].grid(True) # 用户定义的网格外观 axes[1].plot(x, x**2, x, x**3, lw=2) axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)

轴刻度标记线
我们也可以改变轴刻度标记线的参数:


双刻度
有时在图像中采用两个x或y轴是十分有用的,例如单位不同的多条曲线画在一个图中。Matplotlib提供了twinx和twiny函数:


x和y值为0的坐标轴


其他二维绘图样式
除了常规的plot方法,还有一些其他的函数能够实现不同样式的绘图,所有可以绘制的图像种类请见http://matplotlib.org/gallery.html.下面展示一些有用的样式:






文字注释
采用text函数可以完成matplotlib图像的文字注释功能。和文字以及标题一样,它也支持LaTeX格式:


多个子图像的绘制和插入
采用fig.add_axes可以手动将坐标轴加入matplotlib图像中,或者用子图绘制的布局管理器,如subplots,subplot2grid或者gridspec:
subplots
fig, ax = plt.subplots(2, 3)
fig.tight_layout()

subplot2grid


gridspec


add_axes
用add_axes手动添加坐标轴对于添加元素于图像中非常有用:


色图和等高线图
色图和等高线图对于两个变量的绘图函数非常有用。在大多数函数中,我们采用色图编码一个维度的数据。下面列出了一些之前定义好的色图,他们对于确定定制版的色图是一种直接的方法,详见:http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps.

pcolor函数


imshow函数


contour函数


3D 图像
在使用matplotlib中的3D图像之前,我们首先需要创建Axes3D类。3D坐标轴和2D坐标轴创建的方法一样;或者更方便的方法是,在add_axes或者add_subplot中采用projection='3d'关键字参数。
from mpl_toolkits.mplot3d.axes3d import Axes3D
曲面图


三维线框图


带投影的等高线图


改变视角
采用view_init可以改变3D图像的视角,该命令有两个参数,elevation和azimuth角度(度数):


动图
Matplotlib也包含了一个简单的API用来产生一系列图像的动图。采用FuncAnimation函数,我们可以产生由一系列图像组成的视频文件。该函数采用了如下命令:fig图像窗口,func更新图像所用的函数,init_func组织图像的函数,frame产生的帧数,和blit指导动图函数只在帧数变动的时候更新(对于光滑动图而言):

为了使用matplotlib中的动图函数,我们首先调用matplotlib.animation:

生成的动画显示了钟摆的位置作为时间的函数:




Note: 为了产生视频文件,我们需要安装ffmpeg或者avconv. 在Ubuntu上安装的指令:
$ sudo apt-get install ffmpeg
或者(更新的版本)
$ sudo apt-get install libav-tools
在MacOSX中, 尝试:
$ sudo port install ffmpeg
有兴趣的用户可以自行安装,这里不再演示视频文件。

后端
Matplotlib有许多“后端”对产生的图像负责,不同的后端能够更产生不同样式的图和视频。非交互式的后端(如 'agg','svg','pdf'等)是用来产生图像文件(如savefig函数),与此不同,交互式的后端(如Qt4Agg,GTK,MaxOSX)能够运行GUI窗口,供用户进行交互式的使用图像。
可供选择的后端有:

默认后端是agg,它基于栅格图形库,非常适合生成像PNG这样的光栅格式。
通常来说,我们并不需要改变默认后端,但是有时转换到例如PDF或者GTKcariro(如果是Linux系统)时会非常有用,能够更产生高质量矢量图形而不是栅格图。




IPython notebook 内联后端
当我们使用IPython notebook时,可以很方便的用matplotlib后端输出嵌入在notebook的图形文件。要激活这个后端,需要在开始的某处添加:
%matplotlib inline
采用如下格式也能够激活内联后端:
%pylab inline
不同之处在于%pylab inline调用了一系列函数包到全局地址空间(scipy,numpy),然而%matplotlib inline只在内联绘图时才调用。在IPython 1.0+的新的notebook中,建议使用%matplotlib inline,因为它更整洁,对于函数包的调用控制更多。通常,scipy和numpy分别通过如下形式调用:
import numpy as npimport scipy as spimport matplotlib.pyplot as plt
内联后端有一系列的设置选择,可以通过IPython的命令%config来更新InlandBackend中的设置。例如,我们可以转换SVG图像或者更高分别率的图像通过:
%config InlineBackend.figure_format='svg'
或者
%config InlineBackend.figure_format='retina'
如需了解更多内容,请输入:


交互式后端(这使得Python脚本文件更有意义)

注意,当我们采用交互式后端是,需要调用plt.show()命令将图像显示在屏幕上。
推荐阅读
http://www.matplotlib.org- 官方网页
https://github.com/matplotlib/matplotlib- matplotlib源代码
http://matplotlib.org/gallery.html- 展示各种各样matplotlib函数包能够绘制的图像,强烈推荐!
http://www.loria.fr/~rougier/teaching/matplotlib- matplotlib课程
http://scipy-lectures.github.io/matplotlib/matplotlib.html- 其他参考文献
版本

到JoinQuant查看原文并参与讨论:【翻译搬运】Matplotlib - 用Python绘制2D和3D图像
网友评论