当前有效matplotlib版本为:3.4.1。
figure函数概述
在pyplot模块中,figure函数用于创建新的图形,或激活已存在的图形。
函数的签名为matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, clear=False, **kwargs)
函数的参数如下:
num:图形的唯一标识符。可选参数。整数、字符串或Figure对象。可选参数。默认值为None。
当已经存在使用该标识符的图形时,使用该标识符的图形将被激活并返回。对于标识符而言,整数对应Figure.number属性,字符串对应图形的标签。
如果没有对应标识符的图形时,新的图形将会创建。如果参数值为整数则用于Figure.number属性,否则将会自动生成一个整数值(从1开始,每新建一个图像递增1)。如果参数值为字符串,图形标签和窗口标题将设为该值。figsize:图形的尺寸(宽度,高度),默认单位为英寸。可选参数。浮点数二元组。默认值为rcParams["figure.figsize"],即[6.4, 4.8]。dpi:图形的分辨率,即每英寸的像素数。可选参数。浮点数。默认值为rcParams["figure.dpi"],即100。Jupyter Notebook默认值为72,另外由于bbox_inches='tight',因此Jupyter Notebook可能会剪切图形,导致图形的实际大小不可预测。facecolor:图形的背景色。可选参数。颜色值。默认值为rcParams["figure.facecolor"],即'white'。edgecolor:图形的边框色。可选参数。颜色值。默认值为rcParams["figure.edgecolor"],即'white'。frameon:是否绘制图形。可选参数。布尔值。默认值为True。FigureClasss:生成图形时选用的自定义Figure。可选参数。Figure类的子类。默认值为<class 'matplotlib.figure.Figure'>。clear:当图形存在时是否清除原有图形。可选参数。布尔值,值为True时,当图形存在时,原有图形将被清除。默认值为False。tight_layout:是否使用紧凑布局。布尔值或字典。默认值为rcParams["figure.autolayout"],即False。
如果值为False,则使用subplotpars参数调整子图配置参数。如果值为True,则调用tight_layout函数。如果值为字典,字典键即tight_layout函数的参数。subplotpars:子图参数。SubplotParams对象,如果为None,则使用子图的默认参数rcParams["figure.subplot.*"]。constrained_layout: 是否采用约束布局。布尔值或字典。默认值为rcParams["figure.constrained_layout.use"],即False。
如果值为True,则使用约束布局(constrained layout)调整绘图元素的位置。该参数类似于tight_layout。**kwargs:Figure对象的其他属性。
返回值为Figure对象
figure函数相关函数
get_fignums函数:作用为返回已存在的图形编号列表。函数签名为matplotlib.pyplot.get_fignums(),返回值为整数列表。
源码为:
def get_fignums():
"""Return a list of existing figure numbers."""
return sorted(_pylab_helpers.Gcf.figs)
get_figlabels函数:作用为返回已存在的图形标签列表。函数签名为matplotlib.pyplot.get_figlabels(),返回值为字符串列表。
源码为:
def get_figlabels():
"""Return a list of existing figure labels."""
managers = _pylab_helpers.Gcf.get_all_fig_managers()
managers.sort(key=lambda m: m.num)
return [m.canvas.figure.get_label() for m in managers]
get_fignum_exists函数:作用为判断对应编号的图形是否存在。函数签名为matplotlib.pyplot.fignum_exists(num),返回值为布尔值。
源码为:
def fignum_exists(num):
"""Return whether the figure with the given id exists."""
return _pylab_helpers.Gcf.has_fignum(num) or num in get_figlabels()
案例:图形标识符演示
import matplotlib.pyplot as plt
# 获取默认figure对象
fig1 = plt.gcf()
# 生成新的figure对象
fig2 = plt.figure()
# 生成新的figure对象,标识符为1
fig3 = plt.figure(num=1)
# 生成新的figure对象,标识符为first
fig4 = plt.figure(num='first')
# 默认figure对象的编号为1
# 新figure对象的编号为2
# 由于num=1的figure对象已存在,所以未新建figure对象
# 新建figure对象的编号为3
print(fig1.number, fig2.number, fig3.number, fig4.number)
# 由于num=1的figure对象已存在,所以未新建figure对象,fig1==fig3
print(fig1 == fig3)
# 获取当前已存在的figure对象的编号列表
print(plt.get_fignums())
# 检测编号为4的图形是否存在
print(plt.fignum_exists(4))
# 获取当前已存在的figure对象的标签列表
print(plt.get_figlabels())
输出:
1 2 1 3
True
[1, 2, 3]
False
['', '', 'first']
案例:图形大小单位转换
import matplotlib.pyplot as plt
text_kwargs = dict(ha='center', va='center', fontsize=28, color='C1')
# 默认单位为英寸
plt.figure(figsize=(7,5))
plt.text(0.5, 0.5, '7 inches x 5 inches', **text_kwargs)
# 英寸、厘米单位转换
cm = 1/2.54
plt.figure(figsize=(15*cm, 5*cm))
plt.text(0.5, 0.5, '15cm x 5cm', **text_kwargs)
# 英寸、像素单位转换
px = 1/plt.rcParams['figure.dpi']
plt.figure(figsize=(600*px, 200*px))
plt.text(0.5, 0.5, '600px x 200px', **text_kwargs)
plt.show()



案例:使用自定Figure子类
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
# 自定义Figure子类
class WatermarkFigure(Figure):
def __init__(self, *args, watermark=None, **kwargs):
super().__init__(*args, **kwargs)
if watermark is not None:
self.text(0.5, 0.5, watermark,
ha='center', va='center', rotation=30,
fontsize=40, color='gray', alpha=0.5)
plt.figure(FigureClass=WatermarkFigure, watermark='mighty13')
plt.plot([1,1])
plt.show()

本文详细介绍了 matplotlib 中 figure 函数的功能及参数设置方法,并通过实例展示了如何利用这些参数进行图形标识符管理、图形大小单位转换及使用自定义 Figure 子类。
7862





