I pass a function through a loop to fill different figures with subplots.
But there are too many subplots for the figure size (say 20 elements in the loop, resulting in 20 subplots for one figure). So I would like to dynamically assign the subplots to a new figure once the first has been filled (say to fig1b after filling 5 subplots in fig1a).
I would have thought of using if conditions and referring to the axes dynamically (something like ax1_'j' with j a variable). But I have read that dynamical variable naming shouldn't be done in python and I should use a dictionary instead. I don't know how to do that when dealing with figures and axes.
Here is a minimal working example of what I have now:
#Subplot grid settings
Tot = 5
Cols = 2
Rows = 3
Position = range(1,Tot + 1)
fig1 = plt.figure(1, figsize=(10, 7))
fig2 = plt.figure(2, figsize=(10, 7))
def func(i):
ax1 = fig1.add_subplot(Rows, Cols, Position[i])
ax1.plot(range(1, 10), np.ones(9) * i, label="first line")
ax1.plot(range(1, 10), np.ones(9) * 2*i, label="second line")
ax1.set_title(i)
ax1.set_xlabel("x label")
ax2 = fig2.add_subplot(Rows, Cols, Position[i])
ax2.plot(range(1, 10), np.ones(9) *10*i)
return ax1, ax2
# Loop over elements
for i in range(5):
ax1, ax2 = func(i)
# Add common legend to figure 1
handles1, labels1 = fig1.axes[-1].get_legend_handles_labels()
fig1.legend(handles1, labels1, loc='lower right')