0

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

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

fig.savefig("test.png")
plt.show()

Image1

Image2

How can I save these 2 charts into a single PDF with each chart having its own page, instead of having them combined onto a single page?

CDspace
  • 2,639
  • 18
  • 30
  • 36
Dick Thompson
  • 599
  • 1
  • 12
  • 26
  • [pylab_examples example code: multipage_pdf.py](https://matplotlib.org/examples/pylab_examples/multipage_pdf.html) – sascha Nov 17 '17 at 20:19
  • Was typing my answer based on the same without havin seen you comment, sascha. They really have nice examples there. – klaas Nov 17 '17 at 20:42

2 Answers2

2

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.

klaas
  • 1,661
  • 16
  • 24
1

@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()
ZF007
  • 3,708
  • 8
  • 29
  • 48
  • awesome! thanks so much. and do you know if it has functionality to have dynamic names for the PDF? Like if I want to make the name of the file today's date, how would I be able to do that? – Dick Thompson Nov 17 '17 at 21:07
  • Check the code line `with PdfPages('multipage_pdf.pdf') as pdf:` it has the name in it. If you change `multipage_pdf.pdf` into `myfile_2017_11_17.pdf` it should fine. – ZF007 Nov 17 '17 at 21:23
  • but if I wanted to make it dynamic, how would I format it? just a simple datetime function to string? – Dick Thompson Nov 17 '17 at 21:41
  • The script is missing a file creation. Add the code `mypdf = open(“workfile”,”w”)` above the line that starts `with PdfPages...` and replace 'multipage_pdf.pdf' with `mypdf` referral. "workfile" is your filename of your choosing. – ZF007 Nov 17 '17 at 21:43
  • Yeah.. datetime lib got the tools for you. filename = 'myname_%s' % (datetime magic) – ZF007 Nov 17 '17 at 21:46