I think the following does what you want. Note that you use the returned
handle to the first
imshowand add it to the axis for the insert. You need
to make a copy so you have a separate handle for each figure,
import matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axesfrom mpl_toolkits.axes_grid1.inset_locator import mark_insetimport numpy as npimport copydef get_demo_image(): from matplotlib.cbook import get_sample_data import numpy as np f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False) z = np.load(f) # z is a numpy array of 15x15 return z, (-3,4,-4,3)fig, ax = plt.subplots(figsize=[5,4])# prepare the demo imageZ, extent = get_demo_image()Z2 = np.zeros([150, 150], dtype="d")ny, nx = Z.shapeZ2[30:30+ny, 30:30+nx] = Z# extent = [-3, 4, -4, 3]im = ax.imshow(Z2, extent=extent, interpolation="nearest", origin="lower")#Without copy, image is shown in insert onlyimcopy = copy.copy(im)axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6axins.add_artist(imcopy)# sub region of the original imagex1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9axins.set_xlim(x1, x2)axins.set_ylim(y1, y2)plt.xticks(visible=False)plt.yticks(visible=False)# draw a bbox of the region of the inset axes in the parent axes and# connecting lines between the bbox and the inset axes areamark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")plt.draw()plt.show()For your wrapper function, this would be something like,
def plot_with_zoom(*args, **kwargs): im = ax.imshow(*args, **kwargs) imcopy = copy.copy(im) axins.add_artist(imcopy)
However, as
imshowjust displays the data stored in array
Zas an image, I
would think this solution would actually be slower than two separate calls to
imshow. For plots which take more time, e.g. a
contourplot or
pcolormesh, this approach may be sensible…
EDIT:
Beyond a single
imshow, and for multiple plots of different types. Plotting
functions all return different handles (e.g. plot returns a list of lines,
imshow returns a matplotlib.image.AxesImage, etc). You could keep adding these
handles to a list (or dict) as you plot (or use a
collection if they are
similar enough). Then you could write a general function which adds them to an
axis using add_artist or add_patch methods from the zoomed axis, probably with
if type checking to deal with the various types used in the plot. A simpler
method may be to loop over
ax.get_children()and reuse anything which isn’t
an element of the axis itself.
Another option may be to look into blitting techniques,
rasterization
or other techniques used to speed up animation, for example using
fig.canvas.copy_from_bboxor
fig.canvas.tostring_rgbto copy the entire
figure as an image (see why is plotting with Matplotlib so
slow?low). You could also draw the figure, save it to a non-
vector graphic (with
savefigor to a StringIO
buffer), read back in and plot a zoomed
in version.



