Skip to content Skip to sidebar Skip to footer

Saving 2 Plots Into One Pdf With 2 Pages?

Let's say I have from output 2 matplotlib plots in my jupyter notebook (for example purposes these charts are the exact same). import matplotlib.pyplot as plt import numpy as np #

Solution 1:

You could use something like this:

I took your sample code and slightly adapted it to the multipage example from matplotlib.

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

import matplotlib.pyplot as plt
import numpy as np

with PdfPages('multipage_pdf.pdf') as pdf:
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # Note that using plt.subplots below is equivalent to using# fig = plt.figure and then ax = fig.add_subplot(111)#fig, ax = plt.subplots()
    plt.plot(t, s)

    #ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks')#ax.grid()
    plt.title("Page one")
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    plt.title("PAGE TWO")
    # Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)

    # Note that using plt.subplots below is equivalent to using# fig = plt.figure and then ax = fig.add_subplot(111)
    fig, ax = plt.subplots()
    ax.plot(t, s)

    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
        title='About as simple as it gets, folks')
    ax.grid()

    pdf.savefig()
    plt.close()

This results in a nice two page pdf on my mac unsing python 3. This is not intended to be the final solution but should be a good starting point for you oto go on. You can also add pdf metadata, insert text and much more.

multipage pdf sample

remark for osx users: I had problems with the example from matplotlib due to the line:

plt.rc('text', usetex=True)

This resulted in a LaTex error.

RuntimeError: LaTeX was not able to process the following string:
b'lp'
Here is the full report generated by LaTeX: 

Just set

usetex=False

as a first workaround to get going.

Solution 2:

@sascha. Voila the code you referred to. Pages referrals sometimes seem to break after a few years without reason ;-) Teh code example...

#!/usr/bin/env python# -*- coding: utf-8 -*-"""
This is a demo of creating a pdf file with several pages,
as well as adding metadata and annotations to pdf files.
"""import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
    import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:# The with statement makes sure that the PdfPages object is closed properly at# the end of the block, even if an Exception occurs.with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.attach_note("plot of sin(x)")  # you can add a pdf note to# attach metadata to a page
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()

Post a Comment for "Saving 2 Plots Into One Pdf With 2 Pages?"