简体   繁体   中英

Jump to matplotlib axes object based on axes label

In matplotlib it is possible to pass a figure name to a newly created figure:

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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