Matplotlib - Figure 类
Matplotlib - Figure 类
Section titled “Matplotlib - Figure 类”matplotlib.figure.Figure 类是 Matplotlib 中所有绘图元素(plot elements)的顶层容器(top-level container)。可以将其视为绘制所有其他元素(如图形、标题、图例等)的画布(canvas)。
通常情况下,您不会直接实例化(instantiate)Figure。相反,推荐创建 Figure 和关联的 Axes(实际绘图区域)的方式是使用 pyplot.subplots() 函数:
import matplotlib.pyplot as plt
# 创建一个 Figure 和一个单独的 Axesfig, ax = plt.subplots()
# 创建一个包含 2x2 Axes 网格的 Figurefig, axes = plt.subplots(nrows=2, ncols=2)或者,您可以使用 pyplot.figure() 创建一个 Figure,然后手动添加 Axes,这提供了对位置的更多控制:
fig = plt.figure()ax1 = fig.add_subplot(1, 1, 1) # 添加一个标准的子图ax2 = fig.add_axes([0.2, 0.2, 0.4, 0.4]) # 在指定位置 [left, bottom, width, height] 添加一个 Axes使用 plt.figure() 或 plt.subplots() 创建 Figure 时,可以指定几个参数来控制其外观:
| 参数 (Parameter) | 描述 (Description) |
|---|---|
figsize | 以英寸为单位的 (width, height) 元组。控制 Figure 的物理尺寸。 |
dpi | 每英寸点数(Dots Per Inch)。控制 Figure 的分辨率。 |
facecolor | Figure 的背景颜色。 |
edgecolor | Figure 的边框颜色。 |
linewidth | 边框线的宽度。 |
layout | 指定布局引擎(例如,‘constrained’,‘tight’)以自动调整子图参数以实现紧凑布局。推荐使用此参数而非 plt.tight_layout()。 |
# 创建一个具有特定尺寸和分辨率的 Figurefig = plt.figure(figsize=(8, 6), dpi=100, facecolor='lightgray', layout='constrained')ax = fig.add_subplot(111)ax.plot([1, 2, 3], [4, 5, 6])ax.set_title('带有自定义参数的 Figure')plt.show() # 显示 FigureFigure 对象作为主容器,持有对其所有 Axes、艺术家(artists,如线条、文本)、图例(legends)等的引用。您通常会与 Figure 中包含的 Axes 对象进行交互,以执行大多数绘图操作。