You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Matplotlib主Axes获取内嵌Inset Axes并提取绘图数据?

获取Matplotlib内嵌子图(Inset Axes)的数据

我有多个主图axs,其中部分主图内嵌了Inset Axes,想要遍历主Axes来提取内嵌子图里绘制的数据。以下是最小复现示例:

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(1, 3)
x = np.array([0,1,2])
for i, ax in enumerate(axs):
    if i != 1:
        ins = ax.inset_axes([.5,.5,.4,.4])
        ins.plot(x, i*x)
plt.show()

希望实现类似如下逻辑的功能:

data = []
for ax in axs:
    if ax.has_inset():       # 判断ax是否内嵌Inset Axes
        ins = ax.get_inset() # 从ax中获取Inset Axes
        line = ins.get_lines()[0]
        dat = line.get_xydata()
        data.append(dat)
print(data)
# [array([[0., 0.],
#         [1., 0.],
#         [2., 0.]]),
#  array([[0., 0.],
#         [1., 2.],
#         [2., 4.]])]

Matplotlib没有直接提供has_inset()和get_inset()方法,但可以通过主Axes的get_children()方法筛选内嵌子图(Inset Axes本质也是Axes对象),实现需求。

修改后的可运行代码:

import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(1, 3)
x = np.array([0,1,2])
for i, ax in enumerate(axs):
    if i != 1:
        ins = ax.inset_axes([.5,.5,.4,.4])
        ins.plot(x, i*x)

# 提取内嵌子图数据
data = []
for ax in axs:
    # 筛选主ax下的内嵌Axes对象(排除自身)
    inset_axes = [child for child in ax.get_children() if isinstance(child, plt.Axes) and child is not ax]
    if inset_axes:
        # 假设每个主ax仅含一个内嵌子图,取第一个
        ins = inset_axes[0]
        line = ins.get_lines()[0]
        dat = line.get_xydata()
        data.append(dat)

print(data)

关键说明

  • ax.get_children():返回主Axes的所有子元素,包括内嵌Axes、线条、刻度等
  • isinstance(child, plt.Axes):筛选出子元素中的Axes实例,即内嵌子图
  • child is not ax:排除主Axes自身,只保留内嵌的子Axes

运行后输出结果与预期完全一致。

内容的提问来源于stack exchange,提问作者alpelito7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:52:40