matplotlib 有没有一种方法可以通过“询问”嵌入的轴来获得插入轴?

frebpwbc  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(108)

我有几个子图,axs,其中一些带有嵌入轴。我想通过在主轴上迭代来获得插图中绘制的数据。让我们考虑这个最小可重复的例子:

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():       # "asking" if ax has embedded inset
        ins = ax.get_inset() # getting the inset from ax
        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.]])]

ig9co6j1

ig9co6j11#

您可以使用get_children和一个过滤器来检索insets:

from matplotlib.axes import Axes

def get_insets(ax):
    return [c for c in ax.get_children()
            if isinstance(c, Axes)]

for ax in fig.axes:
    print(get_insets(ax))

字符串
输出量:

[<Axes:label='inset_axes'>]
[]
[<Axes:label='inset_axes'>]


对于您的特定示例:

data = []
for ax in fig.axes:
    for ins in get_insets(ax):
        line = ins.get_lines()[0]
        dat = line.get_xydata()
        data.append(dat)


输出量:

[array([[0., 0.],
        [1., 0.],
        [2., 0.]]),
 array([[0., 0.],
        [1., 2.],
        [2., 4.]])]

相关问题