Matplotlib Figure 与 Axes 管理函数
Matplotlib 提供了一系列函数用于创建和管理 Figure 与 Axes 对象。以下列出所有相关函数。
函数列表
| 函数 | 功能 | pyplot | 对应方法 |
|---|---|---|---|
| figure() | 创建或激活 Figure | plt.figure() | - |
| subplots() | 创建 Figure 和 Axes 网格 | plt.subplots() | fig.subplots() |
| subplot() | 按行列索引添加单个子图 | plt.subplot() | fig.add_subplot() |
| subplot2grid() | 在网格指定位置创建子图 | plt.subplot2grid() | - |
| subplot_mosaic() | 标签字符串布局子图 | plt.subplot_mosaic() | fig.subplot_mosaic() |
| axes() | 在当前 Figure 添加 Axes | plt.axes() | fig.add_axes() |
| gca() | 获取当前 Axes | plt.gca() | fig.gca() |
| gcf() | 获取当前 Figure | plt.gcf() | - |
| sca() | 设置当前 Axes | plt.sca(ax) | fig.sca(ax) |
| cla() | 清除当前 Axes | plt.cla() | ax.cla() |
| clf() | 清除当前 Figure | plt.clf() | fig.clear() |
| close() | 关闭 Figure 窗口 | plt.close() | - |
| delaxes() | 从 Figure 移除 Axes | plt.delaxes(ax) | fig.delaxes(ax) |
| fignum_exists() | 检查 Figure 编号是否存在 | plt.fignum_exists(n) | - |
| get_figlabels() | 获取所有 Figure 标签列表 | plt.get_figlabels() | - |
| get_fignums() | 获取所有 Figure 编号列表 | plt.get_fignums() | - |
| twinx() | 创建共享 x 轴的双 y 轴 | plt.twinx() | ax.twinx() |
| twiny() | 创建共享 y 轴的双 x 轴 | plt.twiny() | ax.twiny() |
使用示例
示例 1:gca/gcf/sca 操作当前图表
实例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# 创建第一个 Figure
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# 创建第二个 Figure
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# 检查 Figure 1 是否存在
print(plt.fignum_exists(1)) # True
# 获取所有 Figure 编号
print(plt.get_fignums()) # [1, 2]
# 切换回 Figure 1
plt.figure(1)
ax = plt.gca() # 获取当前 Axes
print(ax.get_title())
# 将当前 Axes 设置为另一个
plt.sca(ax)
plt.title('Switched via sca()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
# 创建第一个 Figure
plt.figure(1)
plt.plot(x, np.sin(x), label='sin(x)')
# 创建第二个 Figure
plt.figure(2)
plt.plot(x, np.cos(x), label='cos(x)')
# 检查 Figure 1 是否存在
print(plt.fignum_exists(1)) # True
# 获取所有 Figure 编号
print(plt.get_fignums()) # [1, 2]
# 切换回 Figure 1
plt.figure(1)
ax = plt.gca() # 获取当前 Axes
print(ax.get_title())
# 将当前 Axes 设置为另一个
plt.sca(ax)
plt.title('Switched via sca()')
plt.show()
True [1, 2]
示例 2:subplot2grid 创建非均匀布局
实例
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): 3行3列的网格
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # 顶部横跨整行
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # 左侧纵跨2行
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # 右上横跨2列
ax4 = plt.subplot2grid((3, 3), (2, 1)) # 右中
ax5 = plt.subplot2grid((3, 3), (2, 2)) # 右下
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Top: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Left: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Right Top: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
import numpy as np
fig = plt.figure(figsize=(10, 6), layout='constrained')
# subplot2grid(shape, loc, rowspan, colspan)
# shape=(3,3): 3行3列的网格
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3) # 顶部横跨整行
ax2 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # 左侧纵跨2行
ax3 = plt.subplot2grid((3, 3), (1, 1), colspan=2) # 右上横跨2列
ax4 = plt.subplot2grid((3, 3), (2, 1)) # 右中
ax5 = plt.subplot2grid((3, 3), (2, 2)) # 右下
x = np.linspace(0, 10, 50)
ax1.plot(x, np.sin(x))
ax1.set_title('Top: colspan=3')
ax2.plot(x, np.cos(x), 'orange')
ax2.set_title('Left: rowspan=2')
ax3.bar(['A','B','C'], [3,7,5])
ax3.set_title('Right Top: colspan=2')
ax4.text(0.5, 0.5, 'Panel 4', ha='center', va='center')
ax5.text(0.5, 0.5, 'Panel 5', ha='center', va='center')
fig.suptitle('subplot2grid Layout', fontsize=14)
plt.show()
示例 3:subplot_mosaic 标签布局
实例
import matplotlib.pyplot as plt
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# 通过标签名访问子图
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Top wide panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Top right')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Bottom left')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes['D'].set_title('D: Bottom right')
fig.suptitle('subplot_mosaic() with Label Access')
plt.show()
import numpy as np
layout = """
AAAB
CCDD
"""
fig, axes = plt.subplot_mosaic(layout, figsize=(10, 6),
layout='constrained')
x = np.linspace(0, 10, 100)
# 通过标签名访问子图
axes['A'].plot(x, np.sin(x))
axes['A'].set_title('A: Top wide panel')
axes['B'].plot(x, np.cos(x), 'orange')
axes['B'].set_title('B: Top right')
axes['C'].bar(['X','Y','Z'], [5, 8, 3], color='steelblue')
axes['C'].set_title('C: Bottom left')
axes['D'].hist(np.random.randn(200), bins=20,
color='coral', edgecolor='white')
axes['D'].set_title('D: Bottom right')
fig.suptitle('subplot_mosaic() with Label Access')
plt.show()
示例 4:twinx/twiny 双轴
实例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# 主 y 轴(左侧)
color1 = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Voltage')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() 创建共享 x 轴的双 y 轴(右侧)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperature')
ax2.set_ylabel('Temperature (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Dual Y-Axes with twinx()')
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots(figsize=(8, 4), layout='constrained')
# 主 y 轴(左侧)
color1 = 'tab:blue'
ax1.plot(x, np.sin(x) * 100, color=color1, label='Voltage')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Voltage (mV)', color=color1)
ax1.tick_params(axis='y', labelcolor=color1)
# twinx() 创建共享 x 轴的双 y 轴(右侧)
ax2 = ax1.twinx()
color2 = 'tab:red'
ax2.plot(x, np.cos(x) * 40 + 50, color=color2, linestyle='--',
label='Temperature')
ax2.set_ylabel('Temperature (°C)', color=color2)
ax2.tick_params(axis='y', labelcolor=color2)
ax1.set_title('Dual Y-Axes with twinx()')
plt.show()
示例 5:cla/clf/close 清理操作
实例
import matplotlib.pyplot as plt
import numpy as np
# 创建 Figure 并绘图
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Original Plot')
print('Before cla():', len(ax.get_lines())) # 1
# cla() 清除 Axes 内容(保留 Axes 和 Figure)
ax.cla()
print('After cla():', len(ax.get_lines())) # 0
# 重新绘图
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('After cla() and replot')
plt.show()
# clf() 清除整个 Figure
plt.clf()
print('After clf():', len(fig.get_axes())) # 0
# close() 关闭 Figure 窗口
plt.close('all')
print('runoob: cleanup complete')
import numpy as np
# 创建 Figure 并绘图
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])
ax.set_title('Original Plot')
print('Before cla():', len(ax.get_lines())) # 1
# cla() 清除 Axes 内容(保留 Axes 和 Figure)
ax.cla()
print('After cla():', len(ax.get_lines())) # 0
# 重新绘图
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_title('After cla() and replot')
plt.show()
# clf() 清除整个 Figure
plt.clf()
print('After clf():', len(fig.get_axes())) # 0
# close() 关闭 Figure 窗口
plt.close('all')
print('runoob: cleanup complete')

Matplotlib 参考文档