Combining your code and the link you gave, this saves one pdf (output.pdf) with 5 pages, and on each page there is one figure:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
import numpy as np
import matplotlib.pyplot as plt
def generate_data():
return np.random.randint(10, size=10)
figs = []
n_figs = 5
for j in range(n_figs): # create all figures
plt.figure(j)
plt.suptitle("figure {}" .format(j+1))
for i in range(4):
plt.subplot(2, 2, i + 1)
plt.plot(generate_data())
for fig in range(0, plt.gcf().number + 1): # loop over all figures
pdf.savefig( fig ) # save each figure in the pdf
pdf.close()
EDIT: after the comment, here is version attempting to use less memory when lots of figures are produced. The idea is to save each figure once it is created, and then to close it.
for j in range(n_figs): # create all figures
plt.figure(j)
plt.suptitle("figure {}" .format(j+1))
for i in range(4):
plt.subplot(2, 2, i + 1)
plt.plot(generate_data())
pdf.savefig(j) # save on the fly
plt.close() # close figure once saved
pdf.close()
EDIT2: here is a third version, I am unsure which of saves more memory. The idea now is, instead of creating and closing many figures, to create only one, save it, clear it, and reuse it.
plt.figure(1) # create figure outside loop
for j in range(n_figs): # create all figures
plt.suptitle("figure {}" .format(j+1))
for i in range(4):
plt.subplot(2, 2, i + 1)
plt.plot(generate_data())
pdf.savefig(1) # save on the fly
plt.clf() # clear figure once saved
pdf.close()