Skip to content

Instantly share code, notes, and snippets.

@salotz
Created March 1, 2019 20:22
Show Gist options
  • Save salotz/8b4542d7fe9ea3e2eacc1a2eef2532c5 to your computer and use it in GitHub Desktop.
Save salotz/8b4542d7fe9ea3e2eacc1a2eef2532c5 to your computer and use it in GitHub Desktop.
Move a matplotlib Axes from one figure to another.
import matplotlib.pyplot as plt
def move_axes(ax, fig, subplot_spec=111):
"""Move an Axes object from a figure to a new pyplot managed Figure in
the specified subplot."""
# get a reference to the old figure context so we can release it
old_fig = ax.figure
# remove the Axes from it's original Figure context
ax.remove()
# set the pointer from the Axes to the new figure
ax.figure = fig
# add the Axes to the registry of axes for the figure
fig.axes.append(ax)
# twice, I don't know why...
fig.add_axes(ax)
# then to actually show the Axes in the new figure we have to make
# a subplot with the positions etc for the Axes to go, so make a
# subplot which will have a dummy Axes
dummy_ax = fig.add_subplot(subplot_spec)
# then copy the relevant data from the dummy to the ax
ax.set_position(dummy_ax.get_position())
# then remove the dummy
dummy_ax.remove()
# close the figure the original axis was bound to
plt.close(old_fig)
@digitalsignalperson
Copy link

@engeir
Copy link

engeir commented Jun 20, 2024

Right, I see. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment