matplotlib 是一个 python 的 2D 绘图库。大量的学术期刊,书籍出版物使用它来绘制专业的数据可视化图表。matplotlib 支持跨平台,可运行在 python 脚本,python 解释器, IPython,Jupyter notebook, web 应用服务器,以及四个 GUI(Graphical User Interface) 工具包中。使用matplotlib ,只需要几行代码,便可绘制折线图,直方图,功率谱(power spectra), 条形图,误差图,散点图等。
1. 安装
pip install matplotlib
2. 导入
ps: 在 jupyter notebook 环境需要添加 %matplotlib inline
,使得绘图生成在 notebook 页面。其他环境需要去掉 %matplotlib inline
。
import matplotlib.pyplot as plt
%matplotlib inline
3. 基本概念
matplotlib 中定义了四个基本概念:figure, axes, axis, artist。准确理解这四个基本概念,能更好的理解和熟练使用 matplotlib 绘制你想要的图表。
为了更直观的理解这四个概念,没有比直接使用 matplotlib 将这些抽象的概念绘制出来更好的方式了。
import numpy as np
figure, axes = plt.subplots(1, 2, figsize=(8, 4))
figure.suptitle("figure")
x = np.linspace(0, 2, 100)
axes1, axes2 = axes
axes1.plot(x, x, label='artist legend')
axes2.plot(x, x**2, label='artist legend')
axes1.set_title("axes 1")
axes2.set_title("axes 2")
axes1.set_xlabel("axis x of axes 1")
axes2.set_xlabel("axis x of axes 2")
axes1.set_ylabel("axis y of axes 1")
axes2.set_ylabel("axis y of axes 2")
axes1.legend()
axes2.legend()
axes1.grid()
axes2.grid()
plt.show()
通过观察绘制出来的图表,我们可以很直观的看到,各个“抽象概念”的在图表中对应的具体表示,以及它们之间的层次关系。
有了这些可视化呈现,再来逐一理解它们,就很容易了。
3.1 figure
从图中可以看出,figure 表示整个绘图区域,它更多扮演的就是一个容器的角色,所有其他绘图元素都必须要包含在 figure 中,通过 figsize 参数限定 figure 大小,同时也限定了绘图区域的大小。此外,通过使用 figure.suptitle(title)
方法,也可以为整个绘图区域,设置一个标题,但这不是必需的(事实上,如果不给 figure 设置标题,我们这里就无法直观感知到它作为容器的存在)。
由此可见,要使用 matplotlib 绘制图表或任何可视化呈现,就必须先显式或隐式(直接使用 plt.plot 等函数绘制时)创建一个 figure 对象。
下面,简单介绍两种最常用的创建 figure 的方法。根据个人习惯,可任选一种方式即可。个人更多使用第二种方式。
3.1.1 plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, clear=False)
plt.figure()
是任何创建 figure 对象的底层工厂函数。它提供创建 figure 了所有细节。
参数 | 描述 |
---|---|
num | 整数或字符串。figure 编号,即 figure 对象的 number 属性,可以理解为 figure 对象的 ID;如果编号为 num 的 figure 在上下文中已经存在,则直接返回存在 figure 引用,而不创建新的 figure; 默认为 None , 会创建一个新的 figure 对象,并将 number 加1 。 |
figsize | 元组。figure 的宽高,单位 英尺。默认值为 matplotlib.rcParams["figure.figsize"] 。 |
dpi | 整数。分辨率。默认值为 matplotlib.rcParams["figure.dpi"] 。 |
facecolor | 字符串或颜色对象。背景颜色。默认为白色。 |
edgecolor | 字符串或颜色对象。边框颜色。默认为白色。 |
frameon | Bool。 |
clear | Bool。为 True 时,清空当前已经存在的 figure 的绘制。默认不清空。 |
代码示例,理解 num 的作用:
figure1 = plt.figure()
print("this is a new figure instance, whose number is {}.\n".format(figure1.number))
figure2 = plt.figure()
print("this is a new figure instance, whose number is {}.\n".format(figure2.number))
figure1_ref = plt.figure(num=1) # 等效于 plt.figure(1)
print("this is a existed figure instance, whose number is {}.\n".format(figure1_ref.number))
if figure1_ref == figure1:
print("figure1_ref is equal to figure1.")
plt.show()
可以看到,上面脚本运行后,并没有显示可见的图表。正如上文所说,figure 仅仅是个容器,真正我们所想到的包含在 figure 容器中,带有坐标系的一个个图表,是下文将要介绍的 axes
。使用 plt.figure()
方法创建的 figure 要显示图表,必须调用 plt.plot()
等绘制函数。代码如下:
# figure 1
plt.figure(figsize=(9, 3))
plt.suptitle("figure 1")
names = ['a', 'b', 'c']
values = [1, 10, 100]
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.show()
# figure 2
plt.figure(figsize=(9, 3))
plt.suptitle("figure 2")
names = ['d', 'e', 'f']
values = [100, 10, 1]
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.show()