I have some code that generates a figure with a single Axes object.
import matplotlib.pyplot as plt
def myfunc():
fig, ax = plt.subplots()
ax.plot(range(5))
return fig, ax
fig, ax = myfunc()
I want to wrap that code such that I can call it multiple times, extract the ax object and collect it into a new figure, essentially creating a composition. I already have some code to move the axes from a figure to another:
def move_axes(ax, original_fig, target_fig, position=None):
"""
Move Axes object from original_fig to target_fig.
Sacrifices original_fig.
# MISSING A CLEVER WAY TO AUTOMATICALLY ESTIMATE THE NEW POSITION.
"""
if position is None:
position = ax.get_position()
ax.remove()
ax.figure = target_fig
target_fig.axes.append(ax)
target_fig.add_axes(ax)
ax.set_position(position)
plt.close(original_fig)
return target_fig
So what I want to do is something like:
target_fig = plt.figure()
for i in range(3):
fig, ax = myfunc()
move_axes(ax, fig, target_fig)
But that doesn't work because I need to set the position of the Axes such that they don't overlap each other. Is there a clean way to do this, i.e., grab the size of the Axes, expand the target_fig
so that every new ax would be stacked vertically below the previous one?