简体   繁体   中英

save multiple figures with subplots into a pdf with multiple pages

I currently have some code like this:

import numpy as np
import matplotlib.pyplot as plt

def generate_data():
    return np.random.randint(10, size=10)

plt.figure(1)
for i in range(4):
    plt.subplot(2, 2, i + 1)
    plt.plot(generate_data())

plt.savefig("C:\\test.pdf")

Suppose if want to generate 5 of these graph each with 4 pictures. How do I save them onto a pdf with the same page.

I have read a few answers on here talking about how to save figures. For example, this one

Python saving multiple figures into one PDF file

However, I don't understand how to create the figures needed.

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()

Like this.

fig, ax = plt.subplots(2, 2) 
for i in range(5):
    ax[i].plot(generate_data())
fig.savefig("C:\\test.pdf")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM