Matplotlib 是 Python 中最常用的数据可视化库之一,支持丰富的图表类型和复杂的布局控制。在实际科研绘图或工程报告中,经常需要在一张主图中嵌入局部放大图、多尺度对比图或组合式图表。这种在一个子图中继续创建子图的技术被称为'子图嵌套'。
本文总结了两种实现子图嵌套的核心方法:基于 axes 对象的 inset_axes 方法和基于 fig 对象的 add_axes 方法。通过深入解析两者的坐标系统差异、参数配置及适用场景,帮助开发者掌握 Matplotlib 的高级布局技巧。
一、inset_axes 方法(Axes 级别)
1. 原理与限制
inset_axes 是 Axes 对象的方法,只能在已经存在的子图(axes)内部插入新的子图。这意味着它适合用于在主图的某个区域内展示细节,例如局部放大或叠加辅助信息。
注意: 该方法必须在 axes 对象上调用,不能在 figure 对象上直接调用,否则会报错。
2. 参数说明
调用 ax.inset_axes(extent, transform=None) 时,主要涉及以下参数:
- extent: 定义新子图的位置和大小。可以是列表形式
[left, bottom, width, height]。- 若未指定 transform,默认单位为当前 axes 的百分比(0~1),相对于 axes 的宽和高。
- 若指定 transform=ax.transData,则单位为数据坐标。
- transform: 可选,用于指定坐标变换方式,如 ax.transAxes 或 ax.transData。
3. 代码示例:百分比定位
以下示例演示如何在第一个子图中插入一个占其尺寸一定比例的子图。
import matplotlib.pyplot as plt
# 设置字体
font1 = {'family': 'Times New Roman', 'size': 15, 'weight': 'bold'}
fig = plt.figure(figsize=(8, 4))
# 创建两个主子图
ax1 = fig.add_subplot(121)
ax1.plot([1, 2, 3], [1, 2, 3])
ax1.set_title('Main Plot 1', font1)
ax2 = fig.add_subplot(122)
ax2.plot([1, 2, 3], [3, 2, 1])
ax2.set_title('Main Plot 2', font1)
extent1 = [, , , ]
ax1_inset = ax1.inset_axes(extent1)
ax1_inset.plot([, , ], [, , ], color=)
ax1_inset.set_title(, font1)
plt.show()


