将2个图表保存为一个包含2页的PDF?

时间:2017-11-17 20:13:44

标签: python pandas pdf matplotlib plot

假设我在我的jupyter笔记本中输出2个matplotlib图(例如,这些图表完全相同)。

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

如何将这两个图表保存为单个PDF,每个图表都有自己的页面,而不是将它们组合到一个页面上?

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

我拿了你的示例代码并稍微调整它到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()

这导致我的mac unsing python 3上有一个很好的两页pdf。 这不是最终的解决方案,但应该是一个很好的起点,你可以继续。 您还可以添加pdf元数据,插入文本等等。

multipage pdf sample

对osx用户的评论:由于该行,我的matplotlib示例出现问题:

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

这导致了LaTex错误。

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

只需设置

usetex=False

作为开始的第一个解决方法。

答案 1 :(得分:1)

@sascha。 Voila您提到的代码。页面推荐有时似乎在没有理由的几年后破坏;-)代码示例......

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