本文转载于 SegmentFault 社区
作者:mhxin
引言
首先来看几个简单的图表, 下面 4 段不同的 matplotlib 绘图代码最终的结果是一样的,绘制的图形如下图所示。
a = np.linspace(-5, 5, 100)
b = np.sin(a)
c = np.cos(a)
# -------------------------------------- #
# ---------------First way-------------- #
fig, ax = plt.subplots()
ax.set_title('Sin-Cos')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.plot(a, b, c='r')
ax.plot(a, c, c='g')
ax.legend(['a', 'b'])
fig.show()
# -------------------------------------- #
# ---------------Second way-------------- #
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Sin-Cos')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.plot(a, b, c='r')
ax.plot(a, c, c='g')
ax.legend(['a', 'b'])
fig.show()
# -------------------------------------- #
# ---------------Third way-------------- #
plt.figure()
plt.title('Sin-Cos')
plt.xlabel('X')
plt.ylabel('Y')
plt.plot(a, b, c='r')
plt.plot(a, c, c='g')
plt.legend(['a', 'b'])
plt.show()
# -------------------------------------- #
# ---------------Fourth way------------- #
plt.subplot(111)
plt.title('Sin-Cos')
plt.xlabel('X')
plt.ylabel('Y')
plt.plot(a, b, c='r')
plt.plot(a, c, c='g')
plt.legend(['a', 'b'])
plt.show()

Matplotlib 中的部件
好了,说了这么多,我们先来了解 matplotlib 绘图过程中几个主要的名称,如下图所示:
- Figure 可以理解为画板,使用 fig = plt.figure() 会创建一个画板。
- Axes可以理解为画板上的各种图形,一个图形就是一个 axes,利用 axes 可以对图形的各个部分进行设置。比如使用 fig.add_subplot() 会在 fig 上创建一个 axes。
- Axis 表示一个 Axes 的坐标轴,比如 x 轴,y 轴以及 z 轴等。

实战
基于上面的介绍,我们来绘制一些图形。时间序列图
直接上代码:# 导入FontProperties类,该类用于定义字体,包括字体,大小等
from matplotlib.font_manager import FontProperties
# 定义标签字体,字体为Time New Roman
# 也可以通过指定fname(字体文件的路径)来定义字体
label_font = FontProperties(family='Times New Roman', size=18, weight='bold', style='normal')
# 定义标题字体
title_font = FontProperties(family='Times New Roman', size=20, weight='bold', style='normal')
# 定义坐标轴刻度字体
ticks_font = FontProperties(family='Times New Roman', size=12, weight='bold', style='normal')
# 定义legend字体
legend_font = FontProperties(family='Times New Roman', size=18, weight='bold', style='normal')