I know this question comes up quite often, but despite reading tens of other SO questions (here, here, here, ... A search for [matplotlib] copy axes
returns almost 200 results!), I couldn't find a solution to my case.
I have a function plotting something and returning the figure and the axes handles E.g.:
import numpy as np
import matplotlib.pyplot as plt
r = np.random.rand
def plot_something():
x = np.linspace(0,10,100)
y = r()*np.sin(r()*x+r())
y2 = r(1000)*10
fig, ax = plt.subplots()
ax.plot(x,y)
ax.hist(y2,density=True)
return fig, ax
In the figure I have multiple artists of different types (e.g. rectangles and lines in the example above).
I want to generate a figure containing several axes (subplots) and, in a loop, call this function multiple times and populate the different axes of the figure.
The point is that I cannot change the first function.
In other words, I would like to do something like this:
fig, axs = plt.subplots(4,4)
for destination in axs.flatten():
fig2, ax = plot_something()
# move/copy everything from ax to destination
plt.close(fig2)