优秀学习资源可以参考官方资源:Matplotlib: Visualization with Python。
Matplotlib 是一个综合库,用于在 Python 中创建静态,动画和交互式的可视化元素。可访问 Sample plots in Matplotlib¶ 快速查看 Matplotlib 的应用的简单例子。
Matplotlib 官方网站提供了许多优质的学习资源:User's Guide、examples gallery 以及 list of plotting commands、External Resources。
1 基础知识
Matplotlib 在Figure
(即窗口,Jupyter 小部件等)上绘制数据图,每个 Figure
都可以包含一个或多个 Axes
(即,可以根据 x-y 坐标(或极坐标中的ther-r)指定点的区域 或 3D 图中的 xyz 等)。用 axes 创建 figure 的最简单方法是使用 pyplot.subplots
。然后,我们可以使用 Axes.plot
在轴域上绘制一些数据:
fig, ax = plt.subplots() # Create a figure containing a single axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plot some data on the axes.
也可以简化为:
plt.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Matplotlib plot.
matplotlib 基本组件包括:Figure
、Axes
、Axis
、Artist
。
1.1 Figure
- 整个图形即是一个
Figure
对象,即一个弹出的绘图的窗口,便是一个 figure。 -
Figure
对象至少包含一个坐标系,也就是Axes
对象。 -
Figure
对象包含一些特殊的Artist
对象,如title
标题、图例legend
。 -
Figure
对象包含画布 canvas 对象。 canvas 对象一般不可见,通常无需直接操作该对象,matplotlib 程序实际绘图时需要调用该对象。
创建新图形的最简单方法是使用 matplotlib.pyplot
:
from matplotlib import pyplot as plt
fig = plt.figure() # an empty figure with no Axes
fig, ax = plt.subplots() # a figure with a single Axes
fig, axes = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes
1.2 Axes
这就是您认为的“绘图”,它是具有数据空间的图像区域。一个给定的 figure
可以包含许多 Axes
,但是一个给定的 Axes
对象只能在一个 Figure
中。一个 Axes
包含两个(或 3D 情况下为三个)Axis
对象(这些对象负责对数据进行限制)。可以使用 axes.Axes.set_xlim()
和 axes.Axes.set_ylim()
限制数据的范围;set_xlabel()
和 set_ylabel()
设置轴指标的描述说明;set_title()
设置标题。
Axes
类及其成员函数是使用 OO 接口的主要入口点。
1.3 Axis
Axis
是数据轴对象,主要用于控制数据轴上刻度位置和显示数值。Axis
有 Locator
和 Formatter
两个子对象,分别用于控制刻度位置和显示数值。
1.4 Artist
基本上所有的对象都是一个 Artist
对象,包括 Figure
对象、Axes
对象和 Axis
对象,可以将 Artist
理解为一个基本类。这包括 Text
对象,Line2D
对象,collections
对象,Patch
对象等。
绘制图形后,所有 artists 都被绘制到画布(canvas)上。 大多数 Artist
都被绑在 Axes
上。Artist
不能被多个轴共享,也不能从一个轴移动到另一个轴。
2 面向对象绘图与 pyplot 绘图
面向对象绘图:
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(0, 2, 100)
# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots() # Create a figure and an axes.
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend() # Add a legend.
pyplot 绘图:
x = np.linspace(0, 2, 100)
plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic') # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
最终的效果图均为:
Matplotlib 的文档和示例同时使用 OO 和 pyplot 方法(功能同样强大),您可以随意使用两者(但是,最好选择其中一种并坚持使用,而不是混合使用)。通常,建议将 pyplot
限制为交互式绘图(例如,在 Jupyter 笔记本中),并建议将 OO 样式用于非交互式绘图(在打算作为较大项目的一部分重用的函数和脚本中)。
实际上,对于将 Matplotlib 嵌入到 GUI 应用程序中的情况,实际上存在第三种方法,即使创建图形,它也会完全删除 pyplot
。 我们不在这里讨论。 有关更多信息,请参见库中的相应部分(在图形用户界面中嵌入 Matplotlib)。
3 Backends
网站和邮件列表上的许多文档都提到“后端”("backend"
),许多新用户可能对该术语感到困惑。其实为了支持所有这些用例,matplotlib 可以提供不同的输出,这些功能中的每一个都称为后端。“前端”是用户面对的代码,即绘图代码,而“后端”则是幕后所有艰苦的工作,以制作图形。后端有两种类型:用户界面后端(用于 pygtk
,wxpython
,tkinter
,qt4
或 macosx
;也称为“交互式后端”)和硬拷贝后端以制作图像文件(PNG,SVG,PDF,PS; 也称为“非交互式后端”)。
有 3 种方式识别后端:
- The
rcParams["backend"]
(default:'agg'
) parameter in yourmatplotlibrc
file - The
MPLBACKEND
environment variable - The function
matplotlib.use()
如果存在多个配置,则列表中的最后一个优先。例如 调用 matplotlib.use()
将覆盖 matplotlibrc
中的设置(可参考 Customizing Matplotlib with style sheets and rcParams)。如果未明确设置任何后端,则 Matplotlib
会根据系统上可用的后端以及 GUI 事件循环是否已在运行,自动检测可用的后端。在 Linux 上,如果未设置环境变量 DISPLAY,则“事件循环”被标识为 "headless"
,这将导致回退到非交互式后端(agg)。