简体   繁体   中英

Save multiple figures in one pdf page, matplotlib

I'm trying to get my figures in just one pdf page, but I don't know how to do this. I found out that it's possible to save multiple figures in a pdf file with 'matplotlib.backends.backend_pdf', but it doesn't work for just one page. Has anyone any ideas ? Convert the figures to just one figure ?

You can use matplotlib gridspec to have multiple plots in 1 window

http://matplotlib.org/users/gridspec.html

from matplotlib.gridspec import GridSpec
import random
import numpy
from matplotlib import pyplot as pl

fig = pl.figure(figsize=(12, 16))
G = GridSpec(2,2)   
axes_1 = pl.subplot(G[0, :])

x = [random.gauss(3,1) for _ in range(400)]
bins = numpy.linspace(-10, 10, 100)
axes_1.hist(x, bins, alpha=0.5, label='x')

axes_2 = pl.subplot(G[1, :])
axes_2.plot(x)

pl.tight_layout()
pl.show()

You can change the rows and column values and can subdivide the sections.

Here is a solution provided by matplotlib:

from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

with PdfPages('foo.pdf') as pdf:
    #As many times as you like, create a figure fig and save it:
    fig = plt.figure()
    pdf.savefig(fig)

    ....
    fig = plt.figure()
    pdf.savefig(fig) 

Voilà

Find a full example here: multipage pdf matplotlib

And by the way, for one figure, you don't need matplotlib.backends.backend_pdf just add pdf extension like so:

plt.savefig("foo.pdf")

The PDF backend makes one page per figure. Use subplots to get multiple plots into one figure and they'll all show up together on one page of the 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