简体   繁体   中英

Python figure and axes object

I have a big unresolved question about the matplotlib Python module.

If I create a figure called [Figure1] , with 2 axes [Ax1, Ax2] , and another figure [Figure2] , is there a function or method that will allow me to export the Ax1 object from Figure1 and redraw it to the Figure2 object?

In general axes are bound to a figure. The reason is, that matplotlib usually performs some operations in the background to make them look nice in the figure.

There are some hacky ways around this , also this one , but the general consensus seems to be that one should avoid trying to copy axes.

On the other hand this need not be a problem or a restriction at all.

You can always define a function which does the plotting and use this on several figures like so:

import matplotlib.pyplot as plt

def plot1(ax,  **kwargs):
    x = range(5)
    y = [5,4,5,1,2]
    ax.plot(x,y, c=kwargs.get("c", "r"))
    ax.set_xlim((0,5))
    ax.set_title(kwargs.get("title", "Some title"))
    # do some more specific stuff with your axes

#create a figure    
fig, (ax1, ax2) = plt.subplots(1,2)
# add the same plot to it twice
plot1(ax1)
plot1(ax2, c="b", title="Some other title")
plt.savefig(__file__+".png")

plt.close("all")

# add the same plot to a different figure
fig, ax1 = plt.subplots(1,1)
plot1(ax1)
plt.show()

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