How to plot saved plot data in a new figure?


Is there a standard way to compute first and then plot something later? For example, I would like to generate a fine contour plot, then use it as a background later.

x = np.linspace(-1,1,1000)
X,Y = np.meshgrid(x,x)
Z = ((X*X + Y*Y) - 0.5)**2 + Y**2
contours = plt.contour(X,Y,Z,100) # Takes a while...
del x, X, Y, Z

I would like to the later plot the contours quickly. What is the "proper" way to do this in general? I can do something like the following, but it seems like a hack (and may be missing important connections: for example, I initially forgot to set the transform which meant that the data was disconnected from the axis scale...)

f = plt.figure()
ax = plt.gca()
for collection in contours.collections:


Have I forgotten anything here? I would have expected that, for any plotting command, the return value could be passed to an axis command, something like

f = plt.figure()
ax = plt.gca()

or maybe even

though a general function to take the object returned by a plot command and plot it on the current axis efficiently would be best.

I can't find this functionality or a description about how to do this. Any suggestions?

Likewise, is there an easy way to "duplicate" a figure (including the axes properties etc.) so one can produce two similar figures with slightly modified parameters?