I'm currently trying to combine multiple plots into a single plot (with sub-plots). Please check out the following code:
import matplotlib.pyplot as plt
a = list(range(1,10))
b = list(map(lambda x: x**2, a))
c = list(map(lambda x: x**3, a))
d = list(map(lambda x: x+200, a))
plots = []
plt.plot(a, b)
plots.append(plt.gcf())
plt.close()
plt.plot(a, c)
plots.append(plt.gcf())
plt.close()
plt.plot(b, c)
plots.append(plt.gcf())
plt.close()
plt.plot(a, d)
plots.append(plt.gcf())
plt.close()
fig, ax = plt.subplots(len(plots))
for i,plot_obj in enumerate(plots, start=1):
print(f"{i=}, {plot_obj=}")
ax[i].set_figure(plot_obj)
plot_obj.show()
plt.tight_layout()
plt.show()
# plt.savefig('temp.png')
The constraints I have are -
- The plots will be created earlier - I'm storing the
figureobjects in a list. - These plots need to be accessed later on in the code and a single figure needs to be created with each of the plot as a sub-plot.
On running the above code, I'm encountering the error - RuntimeError: Can not put single artist in more than one figure while trying to set the figure of each sub-plot. The thought process is to set each sub-plots's figure with the saved figure object. Is there any way to accomplish this ?
Thanks!
plt.figure()without arguments creates a new figure, so what your code appends to theplotslist are those new figures and not the plots that you want.