英文:
Is there a way of getting the inset axes by "asking" the axes it is embedded in?
问题
I have several subplots, axs
, some of them with embedded inset axes. I would like to get the data plotted in the insets by iterating over the main axes. Let's consider this minimal reproducible example:
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()
Is there a way of doing something like:
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.]])]
英文:
I have several subplots, axs
, some of them with embedded inset axes. I would like to get the data plotted in the insets by iterating over the main axes. Let's consider this minimal reproducible example:
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()
Is there a way of doing something like
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.]])]
答案1
得分: 1
以下是翻译好的部分:
你可以使用 [`get_children`](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.get_children.html) 和一个筛选器来检索插图:
```python
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.]])]
英文:
You could use get_children
and a filter to retrieve the 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))
Output:
[<Axes:label='inset_axes'>]
[]
[<Axes:label='inset_axes'>]
For your particular example:
data = []
for ax in fig.axes:
for ins in get_insets(ax):
line = ins.get_lines()[0]
dat = line.get_xydata()
data.append(dat)
Output:
[array([[0., 0.],
[1., 0.],
[2., 0.]]),
array([[0., 0.],
[1., 2.],
[2., 4.]])]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论