简体   繁体   English

根据轴标签跳转到matplotlib轴对象

[英]Jump to matplotlib axes object based on axes label

In matplotlib it is possible to pass a figure name to a newly created figure: 在matplotlib中,可以将图形名称传递给新创建的图形:

plt.figure('figure1')

This is extremely handy when trying to make a previously created figure current, for example. 例如,在尝试使先前创建的图形成为当前图形时,这非常方便。

import matplotlib.pyplot as plt
plt.figure('figure1')
plt.figure('figure2')
plt.figure('figure1')

The fourth line in the above script will go back to the figure created in the second line without necessarily adding a new figure. 上面脚本中的第四行将返回到第二行中创建的图形,而不必添加新图形。

Similarly, it is possible to add an axes to a figure along with a label for the axes. 类似地,可以将轴与轴的标签一起添加到图形中。 The following 下列

import matplotlib.pyplot as plt
fig = plt.figure('figure1')
rect1 = (0.5,0.5,0.5,0.5)
rect2 = (0.2,0.3,0.4,0.5)
fig.add_axes(rect1, label = 'axes1')
fig.add_axes(rect2, label = 'axes2')

Adds axes objects with labels 'axes1' and 'axes2' to the current figure. 将带有标签“ axes1”和“ axes2”的轴对象添加到当前图形。 I would like to know if it is possible to refer back to these axes along the same lines as jumping back to a figure based on it's label. 我想知道是否有可能沿着与基于标签跳回图形相同的直线引用这些轴。 something like 就像是

ax = plt.axes('axes2')

such that later on I can plot a set of data specifically to my axis of choice, but based on the label of the axis. 这样一来,以后我就可以根据选择的轴(但基于轴的标签)绘制一组数据。

ax.plot(XData, YData)

I need to do this because all my data is part of a dictionary which I am designing to be figure and axes-aware. 我需要执行此操作,因为我的所有数据都是字典的一部分,而该字典被设计为可识别图形和轴。 That is the keys in the key-value pairs should become the figure and axis labels. 也就是说,键值对中的键应成为图形和轴标签。 Further more I am plotting several things on each axis, but not at the same time in my loop. 更进一步,我在每个轴上绘制了一些东西,但是在我的循环中没有同时绘制。

Any ideas on whether this is possible? 关于这是否可能的任何想法?

There is no built-in function to get an axes from its label. 没有内置功能可从其标签获取轴。 But you can write one yourself. 但是你可以自己写一个。 Loop over all axes in a figure and return the axes with the desired label. 循环遍历图中的所有轴,并返回带有所需标签的轴。

def get_ax_by_name(fig, name):
    for axi in fig.axes:
        label = axi.get_label()
        if label == name:
            return axi
    return plt.gca()

def func(x,y, figure_name, axes_name):
    fig = plt.figure(figure_name)
    ax = get_ax_by_name(fig, axes_name)
    ax.plot(x,y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM